Home > Mobile >  Insert at given position in link list , in code why we need (pos-2)
Insert at given position in link list , in code why we need (pos-2)

Time:03-22

In the code given below we insert a node at a given position.

My question is: Why do we need to use pos-2 in the for condition?

insertNode(Node *head,int pos,int data)
{
    Node *temp=new Node(data);
    if(pos==1)
    {
        temp->next=head;
        return temp;
    }
    Node * curr=head;
    for(int i=1;i<=pos-2 && curr!=NULL ;i  )
        curr=curr->next;

    if(curr==NULL)
        return head;

    temp->next=curr->next;
    curr->next=temp;
    return head;
}

CodePudding user response:

Some things to note:

We want curr to point to the node that precedes the position where the new node is to be inserted. This is because we will make the insertion happen with curr->next=temp, where temp is the new node.

Since the head node has no predecessor, it is a special case. This occurs when pos is 1.

When pos is 2, the preceding node is the head node. Since curr is initialised as head, it should not move. So also for this case, we don't want the loop to make any iterations.

When pos is 3, the preceding node is the second node in the list. Since curr points at head, it needs to make one step forward, i.e. the loop should iterate just once. This happens when you make the for condition as <=pos-2.

Alternatively, you could reason that we have already dealt with the case where pos is 1, so we could let the loop start at pos=2, and then we can also replace the <= with < which denotes that we want to get to the preceding position, not at the position. And now the loop header looks like this:

for (int i = 2; i < pos && curr != NULL; i  )

This performs the same number of iterations, but maybe it is more readable.

I hope this explains it.

  • Related