Skip to main content
Question Protected by CommunityBot
edited tags
Link
200_success
  • 145.6k
  • 22
  • 191
  • 480
Source Link
Clefairy
  • 433
  • 1
  • 7
  • 15

Insert a Node at the Tail of a Linked List

I've solved this question, but have a small question. In the while loop we check if (temp->next != NULL), why wouldn't work if we check (temp != NULL). Isn't it the same, both checks will get us to the end of the linked list? Also any code review is appreciated!

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node. The given head pointer may be null, meaning that the initial list is empty.

/*
  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)
{
  // creates a temp to hold the last node and set last's data and next
    Node *last = new Node;
    last->data = data;
    last->next = NULL;
    // if the linked list is empty then set head = last
    if (head == NULL) {
        head = last;
    } else { // if the linked list is not empty
        // creates a temp node and sets it to head
        Node *temp = new Node;
        temp = head;
        // uses temp to find the last node
        // Why do we have to use temp->next here instead of temp? wouldn't it be the same?
        while (temp->next != NULL) {
            temp = temp->next;
        }
        // appends the last node with last
        temp->next = last;
    }
    // returns head of linked list
    return head;
}