oneby7

Linked Lists Reversing and rewiring

297. Reverse Linked List

Easy 147 DSA Sheet

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

A singly linked list is a chain of nodes. Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the node you return the same way, as the list from that node on, and shows null as [].

Example 1

head
47192
output
29174

Input: head = [4, 7, 1, 9, 2]

Output: [2,9,1,7,4]

Explanation: The list 4 → 7 → 1 → 9 → 2 becomes 2 → 9 → 1 → 7 → 4. The node holding 2 was last and is now the head, and the node holding 4 was the head and now ends the list.

Example 2

10-20
head
-2010
output

Input: head = [10, -20]

Output: [-20,10]

Explanation: The two nodes swap places. The node holding -20 now points to the node holding 10, which points to null.

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 = [3, 8, 5, 6]

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.