insertAtTail() algorithm

I am unable to understand the working of insertAtTail() function when I dry run it. Could anyone explain it to me?

Hello @ashish_meher,

Suppose you have to create a linked list as following:
1->2->3->4->5

Now, you have two ways to create a link list:

  1. Either by inserting new node at the head (i.e. at leftmost position)
  2. Or by inserting new node at the tail (i.e. at rightmost position)

You wants to understand the second method.

Algorithm:

  1. Check if link list is not empty.

  2. if it is empty i.e. there is no node in the link list. so, make
    head = new node(d);
    [new operator is dynamically creating a node with data d as passed by user and head is pointing to that first node.]

  3. else, iterate through all the nodes of the list to find the last node.
    node *temp = head; // pointing to the first node
    while(temp->next !=NULL) // this would be NULL only for last node, as there is no futher node after it.
    {
    temp=temp->next; //moving to the next node
    }

4.Insert a new node at the tail
tail->next= new node(‘d’);

Hope, this would help.
Give a like if you are satisfied.

Does that mean when I create a new node it points to NULL?
and what about the head pointer? Does it always point to the first node only?

Yes,

  1. the “next” of new node will point to NULL, as that would be the new last node. [new node is not a pointer(it’s the object of class ), it’s data member next will point to NULL ]
  2. the head node will always point to the first node as it’s name suggest.

Hope, this would clear your doubts.

1 Like