Reverse Linked List

Easy

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

Examples

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

Python Solution

def reverse_list(head: ListNode | None) -> ListNode | None:
    prev = None
    while head:
        next_node = head.next
        head.next = prev
        prev = head
        head = next_node
    return prev

JavaScript Solution

function reverseList(head) {
  let prev = null;
  while (head) {
    const next = head.next;
    head.next = prev;
    prev = head;
    head = next;
  }
  return prev;
}

Step-by-Step Explanation

  1. Use three pointers: prev (initially null), current (head), and next.
  2. For each node: save next, point current.next to prev, advance prev and current.
  3. Continue until head is null. prev will be the new head.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

Linked ListRecursion

Related Problems

All Problems