Data Structures | Linked List | Question 3

Last Updated :
Discuss
Comments

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 prev and next pointer as next

C++
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;
}
C
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;
}
Java
void fun(Node[] head_ref) {
    Node temp = null;
    Node current = head_ref[0];

    while (current != null) {
        temp = current.prev;
        current.prev = current.next;
        current.next = temp;
        current = current.prev;
    }

    if (temp != null)
        head_ref[0] = temp.prev;
}
Python
def fun(head_ref):
    temp = None
    current = head_ref[0]

    while current is not None:
        temp = current.prev
        current.prev = current.next
        current.next = temp
        current = current.prev

    if temp is not None:
        head_ref[0] = temp.prev
JavaScript
function fun(head_ref) {
    let temp = null;
    let current = head_ref[0];

    while (current !== null) {
        temp = current.prev;
        current.prev = current.next;
        current.next = temp;
        current = current.prev;
    }

    if (temp !== null)
        head_ref[0] = temp.prev;
}

Assume that reference of head of following doubly linked list is passed to above function 1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6. What should be the modified linked list after the function call?

2 <--> 1 <--> 4 <--> 3 <--> 6 <-->5

5 <--> 4 <--> 3 <--> 2 <--> 1 <-->6.

6 <--> 5 <--> 4 <--> 3 <--> 2 <--> 1.

6 <--> 5 <--> 4 <--> 3 <--> 1 <--> 2

Share your thoughts in the comments