Insert a Node at the Tail of a Linked List

  • + 7 comments

    Here's my solution in C++14. The class definition of SinglyLinkedListNode specifies that the constructor has an argument which is the data part of the node to be inserted.

    SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int num){

    SinglyLinkedListNode* node = new SinglyLinkedListNode(num);
    node->data = num;
    node->next = NULL;
    
    if(head == NULL){
        head = node;
    }
    
    else{
        SinglyLinkedListNode* temp;
        temp = head;
        while(temp->next != NULL){
            temp = temp->next;
        }
        temp->next = node;
    }
    
    return head;
    

    }