<AI/>
enru
All posts

Reverse linked list

LeetCode 206: Reverse a singly linked list in place by flipping the next pointers of its nodes.

Difficulty
Easy
Published
Topics
#linked list#recursion
Open on LeetCode

Problem Description

You are given a singly linked list. Reverse the list and return it.

The list is represented by the following structure.

typescript
class ListNode {
  val: number;
  next: ListNode | null;
}

Constraints

  • The number of nodes in the list is in the range from 1 to 5000
  • The value of each node is in the range from -5000 to 5000

Examples

input output head 1 2 3 4 5 null head 5 4 3 2 1 null

Solution

All we need to do is iterate over all nodes of the linked list and swap the pointers to the next and previous nodes.

typescript
export class ListNode {
  val: number;
  next: ListNode | null;
 
  constructor(val?: number, next?: ListNode | null) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}
 
export const reverseList = (head: ListNode | null): ListNode | null => {
  let prev: ListNode | null = null;
  let curr = head;
 
  while (curr) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
 
  return prev;
};

Complexity Analysis

Time Complexity

O(n), since we iterate over all nodes of the list.

Space Complexity

O(1), since we don't allocate any additional memory.