in DS recategorized by
4,413 views
8 votes
8 votes

Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as $\textit{prev}$ and next pointer as $\textit{next}$.

void fun(struct node **head_ref) 
{ 
    struct node *temp=NULL; 
    struct node *current=*head_ref; 
    while(current!=NULL) 
    { 
        temp=current->prev; 
        current->prev=current->next; 
        current->next=temp; 
        current=current->prev; 
    } 
    if(temp!=NULL) 
        *head_ref=temp->prev; 
} 

Assume that reference of head of following doubly linked list is passed to above function

$1 \leftrightarrow 2 \leftrightarrow 3 \leftrightarrow 4 \leftrightarrow 5 \leftrightarrow 6$. What should be the modified linked list after the function call? 

  1. $2 \leftrightarrow 1 \leftrightarrow 4 \leftrightarrow 3 \leftrightarrow 6 \leftrightarrow 5$
  2. $5 \leftrightarrow 4 \leftrightarrow 3 \leftrightarrow 2 \leftrightarrow 1 \leftrightarrow 6$
  3. $6  \leftrightarrow 5 \leftrightarrow 4 \leftrightarrow 3 \leftrightarrow 2 \leftrightarrow 1$
  4. $6 \leftrightarrow 5 \leftrightarrow 4 \leftrightarrow 3 \leftrightarrow 1 \leftrightarrow 2$
in DS recategorized by
4.4k views

2 Answers

12 votes
12 votes

First let us see how this code works for small Linked List 

edited by

4 Comments

I have 2 questions and it will be great if you can clear it out for me 

  1. in Node 2: shouldn’t the data value be 2 and not 1? how are the previous and next values being assigned and replaced with the previous node when the while loop has already iterated to the 2nd node?
  2. after node 3 when the program moves to the temp!=null part, from where are you getting temp previous value as 3000? not being able to understand as previously at Node 2 it was 1000 right? kindly clarify this please.

 

0
0
bro i have marked the lines in while loop as 1,2,3,4 so now in the node 1,node 2, node 3 parts see the code and see the values in the solution and try to relate them

and yeah actually i draw the diagram of the node once and copied that diagram 3 times and so by mistake i didnt changed the value of node 2

Also the node diagram of nodes 1 , 2 , 3 that i draw  are before entering while loop after while loop the pointers changed and represented as normal text form under the nodes

see them temp value after node 3 got out of while loop is 2000 right it means it is pointing to node 2

in node 2 prev pointer is pointing to 3000 right
0
0
Updated the solution

thnx for pointing the typo there

if u find any other issues with the solution please comment
0
0
1 vote
1 vote
It is simply reversing the elements.
Answer:

Related questions