4,780 views

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;
while(current!=NULL)
{
temp=current->prev;
current->prev=current->next;
current->next=temp;
current=current->prev;
}
if(temp!=NULL)
} 

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$

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

I have a  doubt in 3rd line

whether current point to head or first node ?

as

according to ur example current = 5000 or current = 1000 ?

U should be able to recognise it

now what do you think??
edited by
Bro I got it I have done serious silly mistake.

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.

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
Updated the solution

thnx for pointing the typo there

if u find any other issues with the solution please comment
It is simply reversing the elements.