AceYourInterviews
Checking sign-in…

49. Reverse Linked List

FoundationLinked list pointer mutation

Reverse the direction of the list so the last node becomes the first and the original head becomes the tail. Return the node object that now begins the list.

Reuse the existing node objects and change their links. Creating new nodes with the same values, or merely reversing values inside unchanged nodes, does not satisfy the contract.

Example 1

Input

a(1) → b(2) → c(3) → null

Output

c(3) → b(2) → a(1) → null

Explanation: The returned object is c, not a new node with value 3. The old head a becomes the tail.

Example 2

Input

a(5) → b(5) → null

Output

b(5) → a(5) → null

Explanation: Equal values do not mean equal objects; the two identities must reverse.

Example 3

Input

null

Output

null

Explanation: No nodes and no mutations are needed.

Constraints

  • 0 <= nodes per input list <= 105
  • -231 <= node.value <= 231 - 1
  • Inputs may be null. Lists are acyclic unless this problem explicitly detects a cycle.
Hints
Hint 1

Describe which part of the list is already reversed and which part remains untouched.

Hint 2

Which reference would be lost if you changed current.next immediately?

Hint 3

Save next, redirect current.next to previous, advance previous and current, then return previous.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Three identities

[1,2,3]
"n2"