Reverse a doubly linked list

Easy

Problem

Reverse a doubly linked list by swapping each node's prev and next pointers, and return the new head.

Example 1

Input:  1 ⇄ 2 ⇄ 3 ⇄ 4
Output: 4 ⇄ 3 ⇄ 2 ⇄ 1

Also asked as: Reverse a Doubly Linked list

Test cases

Case 1

Input:    [1,2,3,4]
Expected: [4,3,2,1]

Case 2

Input:    [1,2]
Expected: [2,1]

Case 3

Input:    [5]
Expected: [5]

Case 4

Input:    []
Expected: []

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Swap prev/next for every node

Time O(n)Space O(1)

For each node swap its prev and next pointers; the old tail becomes the new head.

function reverseDLL(head) {
let cur = head, newHead = head;
while (cur) {
[cur.prev, cur.next] = [cur.next, cur.prev];
newHead = cur;
cur = cur.prev; // the old next
}
return newHead;
}