Prepin
Log in

G

Reverse a linked list.

Approach / Explanation

This question is designed to assess your comprehension and execution of linked lists, particularly your skill in adjusting node pointers to reverse the sequence of the list. A linked list is a data structure made up of a series of nodes that collectively represent a sequence. Each node comprises a value and a reference (link) to the subsequent node in the sequence. In a singly linked list, reversing the list entails updating the next pointer of each node so that it points to the preceding node in the list. It’s important to note that a special pointer, known as the "head" pointer, typically marks the beginning of the list, while the next pointer of the last node points to null . Your task is to devise an algorithm that reverses a given singly linked list. Key aspects to consider while addressing this question include: Understanding the linked-list data structure. Capability to manipulate pointers. Taking into account edge cases such as an empty list or a list containing only a single node.

Suggested Answer

A frequently employed iterative method for reversing a singly linked list involves using three pointers: previous which starts off pointing to null (because the first node in the reversed list will link back to null ). current which points to the head of the original list. next that indicates the node following current in the original list. We traverse through the original list, reversing the next pointer of the current node at each step, and then advancing by updating previous to current and current to next . In pseudocode: function reverse_LinkedList(head) { previous = null current = head while(current is not null) { next = current.next current.next = previous previous = current current = next } return previous }

Alternative Answer

Another method is to utilize recursion, which may be slightly more difficult to understand but fundamentally accomplishes the same task. During the recursion, we traverse all the way to the last node while keeping track of the call stack (which contains the preceding nodes). Once we arrive at the end of the list, we begin to unwind, with each node's next pointer being directed to its predecessor (which corresponds to the parent call stack at this stage), thus reversing the pointers. In pseudocode: function recursive_reverse(node, previous = null) { if(node is null) return previous next = node.next node.next = previous return recursive_reverse(next, node) } You initiate the recursion by invoking this function as: recursive_reverse(head) .

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)
Google

Product

AI Candidate AgentCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin | All rights reserved.