Skip to main content

9. Reverse Linked List

easyAsked at Byju's

Reverse a singly linked list in place.

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

Problem

Given the head of a singly linked list, reverse the list and return the reversed list. Implement both an iterative solution and discuss the recursive variant. The list may contain anywhere from zero to five thousand nodes.

Constraints

  • 0 <= n <= 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 = [1,2]
Output
[2,1]

Approaches

1. Store and rebuild

Push values to an array, then rebuild a list in reverse order.

Time
O(n)
Space
O(n)
const arr=[];
while(head){arr.push(head.val);head=head.next;}
let dummy=new ListNode();
let cur=dummy;
for(let i=arr.length-1;i>=0;i--){cur.next=new ListNode(arr[i]);cur=cur.next;}
return dummy.next;

Tradeoff:

2. Iterative three-pointer

Walk the list flipping next-pointers as you go using prev/curr/next. Returns the new head in one pass.

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:

Byju's-specific tips

Byju's interviewers like seeing you 'teach' pointer reversal aloud, mirroring the explainer style of their K-12 video tutoring product.

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 Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →