Reverse a Linked List Hackerrank Solution in C++

In this post, we are going to provide a hackerrank solution to Reverse a Linked List. We created a function in c++ to reverse a linked list.

In this post, we are going to provide a hackerrank solution to Reverse a Linked List. 

Linked list: It is a linear data structure, Each element of the following linked list is called SinglyLinkedListNode.
SinglyLinkedListNode {
      int data;
      SinglyLinkedListNode* next;
 };
 
Each SinglyLinkedListNode is divided into two parts:
  1. The first part contains the data of the element.
  2. The second part contains the address of the next SinglyLinkedListNode in the list (next).

Update: check out  how to reverse a linked list using recursion in c++

Quick Algorithm to reverse a linked list

  1. While(current!=NULL), repeat steps 2, 3 and 4.
  2. Save the next node in the "n" pointer.
  3. Make the current node point to the previous node.
  4. Just update the previous and current node
  5. At last, update the head node to the previous node.

Reverse a Linked List Hackerrank Solution

SinglyLinkedListNode* reverse(SinglyLinkedListNode*&head) {
    
SinglyLinkedListNode*current = head;
SinglyLinkedListNode*prev = NULL;
SinglyLinkedListNode*n;

while(current!=NULL)
{
    //Save the next node
    n=current->next; 
    
    //Make the current node point to previous node
    current->next=prev;
    
    //Just update previous and current node
    prev=current;
    current=n;
    
}
head=prev;
return head;
}
Reverse a Linked List Hackerrank Solution

About this post: In this program, we created a function in c++ to reverse a linked list. This program is the solution to the hackerrank problem for reversing a linked list. If you have any doubts related to this program, Let me know in the comment section.

Related posts:

Linked Lists Data Structure
 Menu Driven Program for Singly Linked List in C++

Post a Comment

Please do not enter any spam link in the comment box.