Reverse A Doubly Linked List

Easy
0/40
Average time to solve is 15m
profile
Contributed by
145 upvotes
Asked in companies
WalmartIBMGoldman Sachs

Problem statement

You are given a doubly-linked list of size 'N', consisting of positive integers. Now your task is to reverse it and return the head of the modified list.


Note:
A doubly linked list is a kind of linked list that is bidirectional, meaning it can be traversed in both forward and backward directions.

Example:

Input: 
4
4 3 2 1

This means you have been given doubly linked list of size 4 = 4 <-> 3 <-> 2 <-> 1.

Output: 
1 2 3 4

This means after reversing the doubly linked list it becomes 1 <-> 2 <-> 3 <-> 4.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line contains an integer 'N', the size of the linked list.
The second line contains 'N' space-separated integers.
Output format :
The output contains all the integers of the reversed doubly linked list.
Note :
You don’t need to print anything. Just implement the given function.
Sample Input 1 :
8
1 2 3 4 5 6 7 8 
Sample Output 1 :
8 7 6 5 4 3 2 1
Explanation for sample output 1
Input: 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6 <-> 7 <-> 8
Output: 8 <-> 7 <-> 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1
Explanation: It's self explanatory.
Sample Input 2 :
5
5 8 4 9 1
Sample Output 2 :
1 9 4 8 5
Constraints :
1 <= 'N' <= 10^3
0 <= 'data' <= 10^3 

Where 'N' is the size of the doubly linked list.

Time Limit: 1 sec
Hint

We need to swap next and prev pointers between every two consecutive nodes.

Approaches (2)
Recursive

The idea is to use recursion and the given function will iterate the doubly linked list in the previous direction by calling itself recursively to reverse it.

 

Base condition = If the node is NULL then return NULL.

Recursive calls = Swap the next and prev pointers.

  • Base condition :
    • If HEAD is equal to NULL or HEAD ->NEXT = NULL then do:
      • Return HEAD.
  • Recursive calls :
    • Take a pointer TEMP = SOLVE(HEAD->NEXT) .
    • TEMP->PREV = NULL .
    • HEAD ->NEXT ->NEXT = HEAD .
    • HEAD->PREV = HEAD->NEXT.
    • HEAD->NEXT = NULL.
    • Return TEMP.
Time Complexity

O(N), where N is the length of the doubly linked list.

 

We are traversing a linked list of size N that takes O(N) time. Hence, the overall Time Complexity is O(N).

Space Complexity

O(N), where N is the length of the doubly linked list.

 

We are making N recursive calls that take O(N) Space Complexity. Hence, the overall Space Complexity is O(N).

Code Solution
(100% EXP penalty)
Reverse A Doubly Linked List
All tags
Sort by
Search icon

Interview problems

better than 100% did it in O(N) time complexity

Node* reverseDLL(Node* head)

{   

    // Write your code here  

    if(head == NULL || head->next == NULL)

    {

        return head;

    } 

    Node* last =NULL;

    Node* current = head;

 

    while(current != nullptr)

    {

        last = current->prev;

        current->prev = current->next;

        current->next=last;

        current = current->prev;

    }

    return last->prev;

}

26 views
0 replies
1 upvote

Interview problems

reversal in single pass (JAVA)

  public static Node reverseDLL(Node head){

        // Write your code here.

        if(head == null || head.next == null) return head;

         /*

         swap(a, b):=>swap(curr.prev, curr.next)

         temp = a; => lastNode = curr.prev;

         a = b;    => curr.prev =  curr.next;

         b = temp; => curr.next = lastNode

         */

 

        Node curr = head;

        Node lastNode = null;

        while(curr != null){

            lastNode = curr.prev;

            curr.prev = curr.next;

            curr.next = lastNode;

            curr = curr.prev;

        }

        return lastNode.prev;

    }

20 views
0 replies
0 upvotes

Interview problems

very easy approach using stack c++

#include<stack>

Node* reverseDLL(Node* head)

{

     Node* temp = head;

      stack<int> st;

     while(temp!=NULL){

        st.push(temp->data);

         temp = temp->next;

}

temp = head;

     while(temp!=NULL){

        temp->data = st.top();

        st.pop();

        temp = temp->next;

}

    return head;

}

25 views
0 replies
0 upvotes

Interview problems

Easy to understand code for a beginner

#include <stack>

 

Node* reverseDLL(Node* head)

{   

    Node* temp = head; 

    stack<int>st; 

 

    while(temp != nullptr){

        st.push(temp -> data); 

        temp = temp -> next; 

    }

    temp = head; 

    while(temp != nullptr){

        temp -> data = st.top(); 

        st.pop();

        temp = temp -> next;

    }

    return head; 

}

55 views
0 replies
1 upvote

Interview problems

Easy python solution

def insert_new_node(new_head, data):

    new_node = Node(data)

    new_node.next = new_head

    

    if new_head:

        new_head.prev = new_node

    

    new_head = new_node

    return new_node

 

def reverseDLL(head):

    new_head = None

 

    while head:

        new_head = insert_new_node(new_head, head.data)

        head = head.next

    

    return new_head

26 views
0 replies
0 upvotes

Interview problems

Code in C++ using Swapping

Node *reverseDLL(Node *head) {

  if (head == nullptr || head->next == nullptr)

    return head;

  Node *current = head;

  Node *last;

  while (current != nullptr) {

    last = current->prev;

    current->prev = current->next;

    current->next = last;

    current = current->prev;

  }

 

  return last->prev;

}

113 views
0 replies
0 upvotes

Interview problems

Easy c++ sol

Node* reverseDLL(Node* head)

{   

    if(head == NULL || head -> next == NULL)

    return head;

    

    Node *curr = head;

    Node *past = NULL;

    Node *forward = NULL;

 

    while(curr != NULL){

        forward = curr -> next;

        curr -> next = past;

        curr -> prev = forward ;

        past = curr;

        curr = forward;

    }   

    head = past;

    return head;

}

106 views
0 replies
0 upvotes

Interview problems

Detail notes

### Detailed Notes on the Approach and Solution

#### Problem Statement Given a doubly linked list (DLL), we need to reverse the list and return the head of the modified list.

#### Class Structure The `Node` class is structured as follows: ```cpp class Node { public:    int data;    Node *next, *prev;    Node()    {        this->data = 0;        next = NULL;        prev = NULL;    }    Node(int data)    {        this->data = data;        this->next = NULL;        this->prev = NULL;    }    Node(int data, Node* next, Node *prev)    {        this->data = data;        this->next = next;        this->prev = prev;    } }; ```

#### Approach 1. **Initial Check**:   - If the `head` is `nullptr`, it means the list is empty. Return `nullptr` immediately as there is nothing to reverse.

2. **Traversal and Swapping**:   - Initialize a `current` pointer to the `head` of the list.   - Initialize a `temp` pointer to `nullptr` which will be used for swapping pointers.   - Traverse through the list using a `while` loop that continues as long as `current` is not `nullptr`.

3. **Swapping Pointers**:   - For each node, swap its `next` and `prev` pointers:     - `temp` is set to `current->prev` (temporarily store the previous pointer).     - `current->prev` is set to `current->next` (swap the `prev` pointer to point to the next node).     - `current->next` is set to `temp` (swap the `next` pointer to point to the previous node).   - Move the `current` pointer to the next node in the original list, which is `current->prev` after swapping.

4. **Updating the Head**:   - After the loop, `temp` will be pointing to the previous node of the original head. This is because `temp` was the previous node stored before the last swap.   - The new head of the reversed list will be `temp->prev`, as `temp` itself is pointing to the old head node.

5. **Return the New Head**:   - Return the updated `head`.

#### Detailed Explanation of the Code ```cpp Node* reverseDLL(Node* head) {    if (!head) return nullptr;

   Node* current = head;    Node* temp = nullptr;

   // Traverse the list    while (current != nullptr) {        // Swap the next and prev pointers        temp = current->prev;        current->prev = current->next;        current->next = temp;                // Move to the next node (which is previous before swapping)        current = current->prev;    }

   // After the loop, temp will be pointing to the new head    // temp->prev will be nullptr because it was the next of the old head    if (temp != nullptr) {        head = temp->prev;    }

   return head; } ```

1. **Initial Check**:   ```cpp   if (!head) return nullptr;   ```   - This line checks if the `head` is `nullptr`. If it is, the function returns `nullptr` because there is no list to reverse.

2. **Initialize Pointers**:   ```cpp   Node* current = head;   Node* temp = nullptr;   ```   - `current` is initialized to the `head` of the list to start traversal.   - `temp` is initialized to `nullptr` to assist in swapping pointers.

3. **Traversal and Swapping**:   ```cpp   while (current != nullptr) {       // Swap the next and prev pointers       temp = current->prev;       current->prev = current->next;       current->next = temp;              // Move to the next node (which is previous before swapping)       current = current->prev;   }   ```   - The `while` loop traverses the list until `current` becomes `nullptr`.   - Within the loop, the `next` and `prev` pointers of the `current` node are swapped.   - `temp` temporarily stores the `prev` pointer of the `current` node.   - The `prev` pointer of the `current` node is updated to its `next` pointer.   - The `next` pointer of the `current` node is updated to the `temp` pointer.   - `current` is moved to the `prev` node, which is the original next node due to swapping.

4. **Update Head**:   ```cpp   if (temp != nullptr) {       head = temp->prev;   }   ```   - After the loop, `temp` points to the previous node of the original head.   - `head` is updated to `temp->prev` to set the new head of the reversed list.

5. **Return the New Head**:   ```cpp   return head;   ```   - The function returns the updated `head`, which is now the head of the reversed list.

#### Example Given a list `4 <-> 3 <-> 2 <-> 1`: - After reversing, the list becomes `1 <-> 2 <-> 3 <-> 4`.

### Summary This approach efficiently reverses a doubly linked list by swapping the `next` and `prev` pointers for each node during traversal and updating the head to the new head of the reversed list.

18 views
0 replies
0 upvotes

Interview problems

C++ Code !!

if(head == NULL || head->next == NULL){

        return head;

    }

        Node *curr = head;

       Node *last = NULL;

 

    while (curr != NULL){

        // last = curr->prev;

        curr->prev = curr->next;

        curr->next = last ;

        last = curr;

        curr = curr->prev;

    }

    return last

 

Connect on me 

  • Linkedin→ www.linkedin.com/in/ravi-kumar-202488271

 

109 views
0 replies
1 upvote

Interview problems

TC-O(N) and SC-O(1) Easysolytion by swapping the Nodes🔥

Node* reverseDLL(Node* head)

{   

    // Write your code here  

    if(head==NULL || head->next==NULL){

        return head;

    } 

    Node* before=NULL;

    Node* current=head;

    while(current != NULL){

        before=current->prev;

        current->prev=current->next;

        current->next=before;

        current=current->prev;

    }

    return before->prev;

 

}

90 views
0 replies
0 upvotes
Full screen
Console