Insert a Node at the Tail of a Linked List

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