Insert a Node at the Tail of a Linked List

Sort by

recency

|

1759 Discussions

|

  • + 0 comments

    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;
    }
    
  • + 0 comments

    A Python solution:

    def insertNodeAtTail(head, data):
        new_node = SinglyLinkedListNode(data)
        if head is not None:
            current = head
            while current.next:
                current = current.next
            current.next = new_node
            return head
        return new_node