Logo for ammarahmed.ca
Easy
May 28, 2025
#linked-list

206. Reverse Linked List

Problem

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

Example 1:

1Input: head = [1,2,3,4,5] 2Output: [5,4,3,2,1] 3

Example 2:

1Input: head = [1,2] 2Output: [2,1] 3

Example 3:

1Input: head = [] 2Output: [] 3

Constraints:

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

      Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

      Approach

      To solve this iteratively, we can iterater over the list by intializing a pointer to the head and iterating while that pointer is not null. On each iteration, we start off by saving the current value's next node to a temp variable. Then, we assing the current value's next reference to our previous node that was also initialized at the start. After that we set the previous value to the current node and assign the current node to that temp variable we saved to continue iterating.

      Complexity

      Time: O(n)

      We iterate through the list once.

      Space: O(1)

      No extra space created.

      Solution

      1func reverseList(head *ListNode) *ListNode { 2 curr := head 3 var prev *ListNode 4 for curr != nil { 5 temp := curr.Next 6 curr.Next = prev 7 prev = curr 8 curr = temp 9 } 10 return prev 11}