Insert a Node at the Tail of a Linked List

Sort by

recency

|

1760 Discussions

|

  • + 0 comments

    // cpp code SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { //ll doestnt exist

        if(head==NULL){
            head= new SinglyLinkedListNode(data);
            return head;
        }
        //ll already exist
        else{
         SinglyLinkedListNode* temp=head;
         while(temp->next!=NULL){
            temp=temp->next;
         }
         temp->next=new SinglyLinkedListNode(data);
         return head;
        }
    

    }

  • + 1 comment

    Here is a simple function in C language, that inserts a node at the tail of the list:

    SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
        SinglyLinkedListNode *newNode = (SinglyLinkedListNode *)malloc(sizeof(SinglyLinkedListNode));
        
        if(head == NULL){
            head = newNode;
            newNode->data = data;
            newNode->next = NULL;
            return head;
        }
        
        SinglyLinkedListNode *temp = head;
        while(temp->next != NULL) {
            temp = temp->next;
        }
        newNode ->data = data;
        temp->next = newNode;
        temp = newNode;
        newNode->next = NULL;
        
        return head;
    
    }
    
  • + 0 comments

    Here a java solution using recursion.

      static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {
            //create the new node
            if(head == null){
                SinglyLinkedListNode node = new SinglyLinkedListNode(data);
                return node;
            }
            //if the head.next is null, I will insert the new node there
            if(head.next == null)
                head.next = insertNodeAtTail(head.next, data);
            //move to the next    
            else    
                insertNodeAtTail(head.next, data);
            return head;
        }
    
  • + 0 comments

    My Java solution with o(n) time complexity and o(1) space complexity:

    static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {
            if(head == null) return new SinglyLinkedListNode(data);
            
            SinglyLinkedListNode curr = head;
            while(curr.next != null) curr = curr.next;
            curr.next = new SinglyLinkedListNode(data);
            return head;
        }
    
  • + 0 comments

    Here is my c++ solution, you can watch this video explanation here : https://youtu.be/zwvWP4YmsoM

    SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
        SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
        if(head != nullptr) {
            SinglyLinkedListNode* curr = head;
            while(curr->next) curr = curr->next;
            curr->next = newNode;
            return head;
        }
        return newNode;
    }