# Reverse A Linked List Hacker Rank Solution In C++

Explanation:- Before solving this problem (reverse a linked list) first see how linked list work for better understand this problem I have created a Full Code of Reverse Linked List so you can understand very well First check the full code and test. After that see the hacker rank solution for reverse a linked list function or segment, paste that colored code in the editor for a successfully compiled solution.

Check:- Geeksforgeeks solution for School, Basic, Easy, Medium, Hard in C++.

Solution:-

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<stack>
using namespace std;

struct node
{
int data;
struct node *next;
}*root=NULL;

void createnode()
{
int x;
struct node *temp=(struct node*)malloc(sizeof(struct node)); //memory allocation
cin>>x;
temp->data=x;
temp->next=root;
root=temp;
}
void deletenode()     // delete node from begning
{
if(root==NULL)
{
return;
}
struct node *temp=root;
root=temp->next;
free(temp);

}

void print()  //for display the list
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
cout<<"-->"<<temp->data;
temp=temp->next;
}
}

void reverse()
{
if(root==NULL)
{
return;
}
stack<struct node*> s; //create stack template for struct node type
struct node *temp;
temp=root;
while(temp!=NULL) // loop to push the refrence of node
{
s.push(temp);
temp=temp->next;
}
temp=s.top();
root=temp;
s.pop();
while(!s.empty())  // loop to poping the refrence of  node
{
temp->next=s.top();
s.pop();
temp=temp->next;
}
temp->next=NULL;

}
int main()
{
int n,i;
cout<<"Enter The Size of Linked List\n";
cin>>n;

cout<<"Enter The Data in Linked List\n";
for(i=0;i<5;i++)
{
createnode();
}
print();
reverse();
cout<<"\n\nOrigional Liked List is ";
print();
return 0;
}

Hacker Ranks Solution For Reverse Linked List

{
{
}