1
votes

I'm currently studying Doubly Linked Lists and want ask something. This is a function for Node insertion at particular position.

"temp" is a pointer to node.

void insertpos(int value,int pos)
    {
        node *s;
        temp=new node;
        s=head;
        for(int i=0;i<pos-1;i++)
        {
            s=s->next;
        }
        temp->data=value;
        if(s->next==nullptr)
       {
           s->next=temp;
           temp->next=nullptr;
           temp->prev=s;
       }
       else
       {

           temp->next=s->next;
           temp->next->prev=temp;
           s->next=temp;
           temp->prev=s;
       }
    }

What does this line of code mean temp->next->prev=temp; The function works perfectly even without this.

I understand that to insert at particular position, you need to start from head and traverse till that (position-1) and set the position's next pointer to temp and temp's next pointer to next pointer of position and temp's previous pointer to position. But this can be achieved by the following three lines of codes

temp->next=s->next;
       s->next=temp;
       temp->prev=s;

So what's the use of this line temp->next->prev=temp; What does this line mean?

2
The best way to figure out pointer-manipulating code: 1) draw the structure on paper; 2) read through the code and draw what happens at each step. (If you're creating the code: draw what should happen at each step and then write code that does it.) - molbdnilo

2 Answers

3
votes

Since you inserting a node between s and s->next, and its a doubly linked list so s->next's previous node should point to the newly inserted node in between which is temp, hence temp->next->prev=temp;

1
votes

Consider two nodes: s<==>n

And u want to insert a third node 'temp' between them.

Let's see line by line meaning of the last 4 lines of the code

temp->next = s->next

This line wwill make the forward link from temp to n: temp->n

temp->next->prev=temp

This line adds the backward link from n to temp.

In other words, this can be read as (temp->next)->prev=temp which simply makes the backward link from n to temp temp<-n

s->next=temp

This will add forward link from s to temp: s->temp

temp->prev=s

This will add backward link from temp to s: s<-temp

Combining all the links, we get: s<==>temp<==>n