oneby7

Linked Lists Doubly linked lists

284. Reverse a Doubly Linked List

Medium

You are given head, the first node of a doubly linked list. Reverse the list, so that the last node comes first and the first node comes last, and return the head of the reversed list.

Each node has a value, val, and two pointers. next points to the following node, and prev points to the node before it. The head's prev is null, and the last node's next is null. The reversed list must keep both directions right. It must also be made of the nodes you were given, with no new nodes. The comment at the top of the starter code shows the node in your language.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 ⇄ 1 ⇄ 6, and the output shows the list you return the same way, with [] for null. The judge also checks every node and every prev pointer. If a node of the returned list is not one of the nodes you were given, the output says so for the first such node, counting the head as node 1. If a prev is wrong, the output names the first node whose prev is wrong. Either message replaces the values.

Example 1

Input: head = [3, -8, 14, 0, 6]

Output: [6,0,14,-8,3]

Explanation: The node holding 6 was last and is now the head, with its prev null. The node holding 3 was the head and now ends the list, with its next null. Every node in between points forward to the node that was before it, and back to the node that was after it.

Example 2

Input: head = [42]

Output: [42]

Explanation: A list of one node is its own reverse. Its prev and next are both null, before and after.

Example 3

Input: head = []

Output: []

Explanation: An empty list reversed is still empty, so the answer is null.

Check your understanding

Work out the answer for this input before you write any code.

head = [5, 1, 9, 2]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.