In this shot, we will learn how to solve a very common interview problem based on linked lists.
In this problem, we are given a head of a linked list that contains some integers. We need to reverse the linked list so that the head now points to the last element, and all the pointers are reversed. Let’s look at the following visual to better understand the problem statement.
So, now that we are clear on what we need to do, we can think about how to approach a solution for this problem.
We will write an iterative solution to solve this problem.
This problem can also be solved with a recursive approach.
We will follow the steps below to solve the problem.
curr = head
, prev = NULL
, and temp = NULL
pointers.curr
becomes NULL
. Inside the loop, we will perform the swapping, as mentioned in the steps below.
temp
to curr->next
.curr->next
to prev
. (Link reversed)prev
= curr
and curr
= temp
for the next iteration.Let’s now look at the code and see how this will work.
node * reverse(node *head){if(head == NULL || head -> next == NULL)return head;node* current = head;node* prev = NULL;node* temp;while(current!= NULL){temp = current->next;current->next = prev;prev = current;current = temp;}return prev;}int main() {createLinkedList();cout << "The original linked list is: ";printLinkedList(head);node * reverseHead = reverse(head);cout << "\nThe reversed linked list is: ";printLinkedList(reverseHead);}
reverse()
function that accepts the head pointer of the linked list. (We will only learn to implement this function).createLinkedList()
function which will create a linked list that contains some integers.reverse()
function that we just created.Check out my course Competitive Programming - Crack Your Coding Interview, C++ for additional help on how to prepare for coding interviews.