TIC
The Interns Company

Reverse Linked List

EasyAcceptance: 72.5%

Problem Statement

Given the head of a singly linked list, reverse the list, and return the reversed list.

Constraints:

  • The number of nodes in the list is the range [0, 5000]
  • -5000 <= Node.val <= 5000

Input Format:

  • The head of a linked list

Output Format:

  • The head of the reversed linked list

Examples:

Example 1:

Input:

head = [1,2,3,4,5]

Output:

[5,4,3,2,1]

Explanation:

The linked list 1->2->3->4->5 is reversed to 5->4->3->2->1

Example 2:

Input:

head = [1,2]

Output:

[2,1]

Explanation:

The linked list 1->2 is reversed to 2->1

Solutions

Iterative Approach

Time: O(n)
Space: O(1)

Use three pointers to reverse the links between nodes.

Recursive Approach

Time: O(n)
Space: O(n) - due to recursion stack

Recursively reverse the rest of the list and reattach the current node.

Algorithm Walkthrough

Example input: nums = [1,2,3,4,5]

Step-by-step execution:

  1. initial: 1->2->3->4->5
  2. prev=null, current=1, next=2
  3. Change 1->next to null: null<-1 2->3->4->5
  4. prev=1, current=2, next=3
  5. Change 2->next to 1: null<-1<-2 3->4->5
  6. prev=2, current=3, next=4
  7. Change 3->next to 2: null<-1<-2<-3 4->5
  8. prev=3, current=4, next=5
  9. Change 4->next to 3: null<-1<-2<-3<-4 5
  10. prev=4, current=5, next=null
  11. Change 5->next to 4: null<-1<-2<-3<-4<-5
  12. prev=5, current=null
  13. Return prev (5): 5->4->3->2->1

Hints

Hint 1
Think about using pointers to track the previous, current, and next nodes.
Hint 2
Try to solve it both iteratively and recursively.