# Reverse a Linked List Using Stack

Reverse a Linked List Using Stack” is very popular programming problem based on linked list and stack data structures. Here, we are given a linked list and our task is to reverse a linked list using stack.

Example:

```Suppose, we need to reverse the following linked list:
12 -> 13 -> 14 -> 15 -> 16
After reversing the list:
16 -> 15 -> 14 -> 13 -> 12```

The steps required to reverse a linked list using stack are as follows:

1. If the linked list is empty, then simply return.
2. Initialize a stack which can contains nodes.
3. Push all the nodes in a stack except last nodes of a linked list.
5. Now, pop every node in stack and insert them at the end of the newly headed linked list.
6. Print the reversed Linked List.

#### C++Program to reverse a linked list using stack is as follows:

```/* C++ Program to Reverse a Linked List Using Stack */
#include<bits/stdc++.h>
using namespace std;

/* Strcutre of node of the Linked List */
typedef struct node
{
int data;
struct node *next;
}Node;

/* Function to Insert a Node at the end of the Linked List */
{
/* Creating a New Node */
Node *new_node = new Node();
new_node -> data = ele;
new_node -> next = NULL;

/* Check whether Linked List is empty or not */

{
return;
}

/* If Linked List is not empty, traverse the complete linked list and
points the pointer of the last node of the linked list to the new node */
while(temp->next != NULL)
temp = temp -> next;
temp -> next = new_node;
}

/* Function to Print the Linked List */
{
while(temp != NULL)
{
cout << temp -> data << " ";
temp = temp -> next;
}
cout<<endl;
}

/* Function to Reverse a Linked List */
{
/* Create a stack(using STL) of Node structure type */
stack<Node*>st;

/* Insert all the nodes of the Linked List except last node */
while(temp->next != NULL)
{
st.push(temp);
temp = temp ->  next;
}

/* Make Last Node the new head of the linked list */

/* One-by-one pop all the nodes from the linked list
and insert at the end of the linked list */
while(!st.empty())
{
temp -> next = st.top();
temp = temp -> next;
st.pop();
}
temp -> next = NULL;
}
int main()
{
/* Inserting some nodes to the Linked List */

/* Reverse a Linked List */

```OUTPUT: