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-&gt;data = data;
    last-&gt;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-&gt;next here instead of temp? wouldn't it be the same?
        while (temp-&gt;next != NULL) {
            temp = temp-&gt;next;
        }
        // appends the last node with last
        temp-&gt;next = last;
    }
    // returns head of linked list
    return head;
}
Memory Leak
These lines here create a memory leak, because you allocate a node and never free it:

    // creates a temp node and sets it to head
    Node *temp = new Node;
    temp = head;


You don't need to allocate another node there, because you aren't actually ever using it.  You can just set the temp pointer directly to head:
    Node *temp = head;