Given a linked list reverse it without using any additional space (In O(1) space complexity)
belongs to collection: Interview C++ coding problems/challenges | Linked list
All Answers
total answers (1)
belongs to collection: Interview C++ coding problems/challenges | Linked list
total answers (1)
Reversing a single linked list is about reversing the linking direction. We can solve the above problem by following steps:
1. Building the linked list
Firstly, we build the linked list by inserting each node at the beginning. For detailed analysis of how to build a linked list using insertion at beginning, kindly go through this full article: Single linked list insertion
2. Function to reverse the link list
As told previously, the basic idea to reverse a linked list is to reverse the direction of linking. This concept can be implemented without using any additional space. We need three pointers *prev, *cur, *next to implement the function. These variables are named accordingly to indicate their serving part in the function.
*prev - to store the previous node which will become ultimately the next node after reversal for current node
*cur - to store the current node
*next - to store the next node which will become current node in the next iteration.
Initialize *prev & *next to NULL, *cur to head
3. Print the reversed linked list
Example:
C++ program to reverse a single linked list
Output
need an explanation for this answer? contact us directly to get an explanation for this answer