noodleProblems/
Reverse Linked List
#109

Reverse Linked List

AlgorithmeasyLinked ListRecursion

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

Your function receives and returns a ListNode chain; the examples below show each list in array notation for readability — [1, 2, 3, 4, 5] is the chain 1 -> 2 -> 3 -> 4 -> 5, which reverses to 5 -> 4 -> 3 -> 2 -> 1.

Example cases

  • odd length
    in head = [1,2,3,4,5]12345null
    out [5,4,3,2,1]54321null
    1->2->3->4->5 reverses to 5->4->3->2->1.
  • two nodes
    in head = [1,2]12null
    out [2,1]21null
  • empty list
    in head = []null
    out []null

Constraints

  • The number of nodes in the list is in the range [0, 5000].
  • -5000 <= Node.val <= 5000
Saved
head =
[1,2,3,4,5]