0 votes
192 views
in Data Structure And Algorithm by
How to insert at end of a linked list in java?

1 Answer

0 votes
by (5k points)
See the following example to insert at end of a linked list:-

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;
    }
}

package linkedlist;

public class LinkedList<T> {
    Node<T> head;
   
    public void doAppend(T data){
        //Creating new Node with null next pointer
        Node<T> node = new Node<T>(data);
        Node<T> newNode = node;
        //head is empty or inserting first node in linkedlist
        if(head == null){
            head = newNode;
            return;
        }
        //head having some nodes then go to last node which having next node is null pointer
        Node<T> temp = head;
        while(temp.getNext() != null){
            temp = temp.getNext();
        }
        temp.setNext(newNode);
    }

    public void doPrint(){
        Node<T> temp = head;
        while(temp != null){
            System.out.print(temp.getData()+"  ");
            temp = temp.getNext();
        }
    }
}

package linkedlist;

public class LinkedListTest {

    /**
     * @param args
     */
    public static void main(String[] args) {       
        System.out.println("\nPrint All String Using doAppend():");
        LinkedList<String> strlist = new LinkedList<String>();
        strlist.doAppend("A");
        strlist.doAppend("B");
        strlist.doAppend("C");
        strlist.doAppend("D");
        strlist.doAppend("E");
        strlist.doPrint();
    }
}

Output:-
Print All Integer Using doAppend():
A B C D E

Share:- Whatsapp Facebook Facebook


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

Categories

...