FrontendInterviews.dev

Loading problem…

84. Reverse Linked List - Navigation History

Easy•

You're building a browser navigation feature that needs to reverse the order of visited pages. Given a linked list of page visits, you need to reverse the list to show pages in reverse chronological order (most recent first).

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

Requirements

1. Basic Functionality

  • Reverse the order of nodes in the linked list
  • Return the new head (previously the tail)
  • Handle edge cases: empty list, single node

2. Constraints

  • Must reverse in-place (O(1) extra space) or with minimal space
  • Cannot modify node values, only pointers
  • Must handle null/empty list

Example Usage

// Input: 1 -> 2 -> 3 -> 4 -> 5 -> null
// Output: 5 -> 4 -> 3 -> 2 -> 1 -> null

const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
// ... more nodes

const reversed = reverseList(head);
// reversed is now 3 -> 2 -> 1 -> null

Real-World Context

This problem models real-world scenarios:

  • Browser history: Reverse navigation order to show recent pages first
  • Undo/Redo systems: Reverse action history
  • Message threads: Display messages in reverse chronological order
  • Playlist reversal: Reverse song order in a playlist
  • Transaction logs: Display transactions in reverse order

Constraints

  • The number of nodes in the list is the range [0, 5000]
  • -5000 <= Node.val <= 5000
  • Must reverse in-place (O(1) space) or minimal space
  • Cannot modify node values, only pointers
Accepted19/21|Acceptance Rate90.5%