Skip to main content

10. Reverse Linked List

easyAsked at Swiggy

Reverse the direction of every pointer in a singly linked list.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given head of a singly linked list, reverse it and return the new head. Solve both iteratively and recursively.

Constraints

  • 0 <= nodes <= 5000
  • -5000 <= node.val <= 5000

Examples

Example 1

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

Example 2

Input
head=[]
Output
[]

Approaches

1. Push to array then rewrite

Collect node refs into an array and rewire.

Time
O(n)
Space
O(n)
const arr=[];
for (let n=head; n; n=n.next) arr.push(n);
for (let i=arr.length-1;i>0;i--) arr[i].next=arr[i-1];
if (arr.length) arr[0].next=null;
return arr[arr.length-1]||null;

Tradeoff:

2. Iterative three pointer

Walk forward while flipping each node's next pointer to the previous node. Track prev, curr, and next so you do not lose the rest of the list.

Time
O(n)
Space
O(1)
function reverseList(head) {
  let prev = null, curr = head;
  while (curr) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}

Tradeoff:

Swiggy-specific tips

Swiggy expects you to draw the three pointers on the whiteboard before coding; this discipline carries into the dispatch-queue rewiring questions later in the loop.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Reverse Linked List and other Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →