0 votes
407 views
in Data Structure And Algorithm by
Delete a node from Linked List at a given position

For example:-
Node a = [E  D  C  A];
Position = 1;
Final Node = [D  C  A ]

1 Answer

0 votes
by (3.7k points)
See the following running code for delete a node from linked list at the given position:-

package linkedlist;

public class Node<T> {
    private T data;
    private Node<T> next;
   
    public Node(T data){
        this.data = data;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Node<T> getNext() {
        return next;
    }

    public void setNext(Node<T> next) {
        this.next = next;
    }
}

public void doDeleteOnPosition(int position){
        Node<T> temp = head, prev = null;
        int counter = 0;
        if(temp != null && position == 0){
            head = temp.getNext();
            return;
        }
        while(temp != null && counter != position){
            prev = temp;
            counter++;
            temp = temp.getNext();
        }
        if(temp == null){
            System.out.println("Position not found:"+position);
            return;
        }
        prev.setNext(temp.getNext());
    }

 package linkedlist;

public class LinkedListTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
           System.out.println("\nPrint All String Using doAdd():");
        LinkedList<String> strfrontlist = new LinkedList<String>();
        strfrontlist.doAdd("A");
        strfrontlist.doAdd("B");
        strfrontlist.doAdd("C");
        strfrontlist.doAdd("D");
        strfrontlist.doAdd("E");
        strfrontlist.doPrint();
                System.out.println("\nDelete Node at 0 position:-");
        strfrontlist.doDeleteOnPosition(0);
        strfrontlist.doPrint();
       }
}

Output:-
Print All String Using doAdd():
E  D  C  B  A  
Delete Node at 0 position:-
D  C  B  A  
------------------------------------------
Print All String Using doAdd():
E  D  C  B  A  
Delete Node at 0 position:-
E  D  C  A

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...