Linked List: Add a new node at the end of the linked list

Question: Write a function add(Listnode node) function to add a new node at the end of the linked list

public class LinkedList {
    //data fields
    //head node
    ListNode head;

    //constructor to initialize head node
    public LinkedList(){
        head=null;
    }

    //function to add node to the end of the linked list
    public void add(ListNode node){
        //if list is empty then set head equal to the node
        if(head==null){
            head = node;
            node.setNext(null);
        } else {
            //create a pointer- temp
            ListNode temp= head;
            //iterate to the last element
            while(temp.getNext()!=null){
              temp=temp.getNext();
            }
            //insert the node at the end of the list
            temp.setNext(node);
            node.setNext(null);
        }
    }

}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.