July 4, 2017 Andrey

Insert a node into Linked list with C++

Check if Linked List is null and just create a Node.
Otherwise, run to the end of the linked list and insert a node at the end.

/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Insert(Node *head,int data)
{
    if (!head){
        Node *node = new Node();
        node->data = data;
        return node;
    } 
    
    Node *temp = head;  
    while (true) {
        if (!temp->next){
            Node *node = new Node();
            node->data = data;
            temp->next = node;
            return head;
        } 
        temp = temp->next;
    }
}