Reverse a singly linked list iteratively and recursively
Reported in HCLTech interview loops. Pointer manipulation staple for junior coding interviews.
Interview scenario
Often asked in HCLTech technical or coding rounds. Prepare a clear spoken answer plus key trade-offs.
Model answer
Try answering aloud first
Cover trade-offs, structure, and a concrete example before revealing the baseline response.
How to frame this at HCLTech: Connect your answer to measurable impact, clarity of thought, and trade-offs the team cares about. Below is a strong baseline response you can adapt with your own project examples.
Iterative approach uses three pointers: prev, curr, next. Rewire curr.next to prev, advance all pointers until curr is null; return prev as new head.
function reverseList(head) {
let prev = null, curr = head;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Recursive: reverse rest of list, then set head.next.next = head and head.next = null. Base case: empty or single node.
Time O(n), space O(1) iterative or O(n) recursion stack. Mention reversing in groups, palindrome check, and cycle detection (Floyd) as follow-ups.
Discussion
Comments (0)
Share how this question came up in your loop, or add tips for others preparing.
Log in to comment on this question.