NoobLearner
NoobLearner

Reputation: 61

Doubly linked List Node insertion at position

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?

Upvotes: 1

Views: 3341

Answers (2)

Krishna Choudhary
Krishna Choudhary

Reputation: 625

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

Upvotes: 1

Rajeev Singh
Rajeev Singh

Reputation: 3332

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;

Upvotes: 3

Related Questions