Open In App

Program to reverse a linked list using Stack

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list. The task is to reverse the order of the elements of the Linked List using an auxiliary Stack.

Examples: 

Input : List = 3 -> 2 -> 1
Output : 1 -> 2 -> 3

Input : 9 -> 7 -> 4 -> 2
Output : 2 -> 4 -> 7 -> 9 

Algorithm

  1. Traverse the list and push all of its nodes onto a stack.
  2. Traverse the list from the head node again and pop a value from the stack top and connect them in reverse order.

Below is the implementation of the above approach: 

C++




// C/C++ program to reverse linked list
// using stack
  
#include <bits/stdc++.h>
using namespace std;
  
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
  
/* Given a reference (pointer to pointer) to
   the head of a list and an int, push a new 
   node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
  
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
  
// Function to reverse linked list
Node *reverseList(Node* head)
{
    // Stack to store elements of list
    stack<Node *> stk;
  
    // Push the elements of list to stack
    Node* ptr = head;
    while (ptr->next != NULL) {
        stk.push(ptr);
        ptr = ptr->next;
    }
  
    // Pop from stack and replace
    // current nodes value'
    head = ptr;
    while (!stk.empty()) {
        ptr->next = stk.top();
  
        ptr = ptr->next;
        stk.pop();
    }
      
    ptr->next = NULL;
      
    return head;
}
  
// Function to print the Linked list
void printList(Node* head)
{
    while (head) {
        cout << head->data << " ";
        head = head->next;
    }
}
  
// Driver Code
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
  
    /* Use push() to construct below list 
    1->2->3->4->5 */
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
  
    head = reverseList(head);
  
    printList(head);
  
    return 0;
}


Java




// Java program to reverse linked list 
// using stack 
import java.util.*;
class GfG 
  
/* Link list node */
static class Node
    int data; 
    Node next; 
}
static Node head = null;
  
/* Given a reference (pointer to pointer) to 
the head of a list and an int, push a new 
node on the front of the list. */
static void push( int new_data) 
    Node new_node = new Node(); 
  
    new_node.data = new_data; 
    new_node.next = (head); 
    (head) = new_node; 
  
// Function to reverse linked list 
static Node reverseList(Node head) 
    // Stack to store elements of list 
    Stack<Node > stk = new Stack<Node> (); 
  
    // Push the elements of list to stack 
    Node ptr = head; 
    while (ptr.next != null
    
        stk.push(ptr); 
        ptr = ptr.next; 
    
  
    // Pop from stack and replace 
    // current nodes value' 
    head = ptr; 
    while (!stk.isEmpty())
    
        ptr.next = stk.peek(); 
        ptr = ptr.next; 
        stk.pop(); 
    
    ptr.next = null
      
    return head; 
  
// Function to print the Linked list 
static void printList(Node head) 
    while (head != null
    
        System.out.print(head.data + " "); 
        head = head.next; 
    
  
// Driver Code 
public static void main(String[] args) 
    /* Start with the empty list */
    //Node head = null; 
  
    /* Use push() to construct below list 
    1->2->3->4->5 */
    push( 5); 
    push( 4); 
    push( 3); 
    push( 2); 
    push( 1); 
  
    head = reverseList(head); 
  
    printList(head); 
}
  
// This code is contributed by Prerna Saini.


Python3




# Python3 program to reverse a linked
# list using stack 
  
# Link list node 
class Node:
      
    def __init__(self, data, next):
        self.data = data
        self.next = next
  
class LinkedList:
      
    def __init__(self):
        self.head = None
          
    # Function to push a new Node in 
    # the linked list 
    def push(self, new_data): 
      
        new_node = Node(new_data, self.head) 
        self.head = new_node
      
    # Function to reverse linked list 
    def reverseList(self): 
      
        # Stack to store elements of list 
        stk = []
      
        # Push the elements of list to stack 
        ptr = self.head 
        while ptr.next != None
            stk.append(ptr) 
            ptr = ptr.next
      
        # Pop from stack and replace 
        # current nodes value' 
        self.head = ptr 
        while len(stk) != 0
            ptr.next = stk.pop() 
            ptr = ptr.next
          
        ptr.next = None
      
    # Function to print the Linked list 
    def printList(self):
          
        curr = self.head
        while curr: 
            print(curr.data, end = " "
            curr = curr.next
  
# Driver Code 
if __name__ == "__main__":
  
    # Start with the empty list
    linkedList = LinkedList() 
  
    # Use push() to construct below list 
    # 1.2.3.4.5
    linkedList.push(5
    linkedList.push(4
    linkedList.push(3
    linkedList.push(2
    linkedList.push(1
  
    linkedList.reverseList() 
  
    linkedList.printList() 
  
# This code is contributed by Rituraj Jain 


C#




// C# program to reverse linked list 
// using stack 
using System;
using System.Collections.Generic;
  
class GfG 
  
/* Link list node */
public class Node 
    public int data; 
    public Node next; 
static Node head = null
  
/* Given a reference (pointer to pointer) to 
the head of a list and an int, push a new 
node on the front of the list. */
static void push( int new_data) 
    Node new_node = new Node(); 
  
    new_node.data = new_data; 
    new_node.next = (head); 
    (head) = new_node; 
  
// Function to reverse linked list 
static Node reverseList(Node head) 
    // Stack to store elements of list 
    Stack<Node > stk = new Stack<Node> (); 
  
    // Push the elements of list to stack 
    Node ptr = head; 
    while (ptr.next != null
    
        stk.Push(ptr); 
        ptr = ptr.next; 
    
  
    // Pop from stack and replace 
    // current nodes value' 
    head = ptr; 
    while (stk.Count != 0)
    
        ptr.next = stk.Peek(); 
        ptr = ptr.next; 
        stk.Pop(); 
    
    ptr.next = null
      
    return head; 
  
// Function to print the Linked list 
static void printList(Node head) 
    while (head != null
    
        Console.Write(head.data + " "); 
        head = head.next; 
    
  
// Driver Code 
public static void Main(String[] args) 
    /* Start with the empty list */
    //Node head = null; 
  
    /* Use push() to construct below list 
    1->2->3->4->5 */
    push( 5); 
    push( 4); 
    push( 3); 
    push( 2); 
    push( 1); 
  
    head = reverseList(head); 
  
    printList(head); 
}
  
// This code contributed by Rajput-Ji


Javascript




<script>
  
      // JavaScript program to reverse linked list
      // using stack
      /* Link list node */
      class Node {
        constructor() {
          this.data = 0;
          this.next = null;
        }
      }
      var head = null;
  
      /* Given a reference (pointer to pointer) to
         the head of a list and an int, push a new
         node on the front of the list. */
      function push(new_data) {
        var new_node = new Node();
  
        new_node.data = new_data;
        new_node.next = head;
        head = new_node;
      }
  
      // Function to reverse linked list
      function reverseList(head) {
        // Stack to store elements of list
        var stk = [];
  
        // Push the elements of list to stack
        var ptr = head;
        while (ptr.next != null) {
          stk.push(ptr);
          ptr = ptr.next;
        }
  
        // Pop from stack and replace
        // current nodes value'
        head = ptr;
        while (stk.length != 0) {
          ptr.next = stk[stk.length - 1];
          ptr = ptr.next;
          stk.pop();
        }
        ptr.next = null;
  
        return head;
      }
  
      // Function to print the Linked list
      function printList(head) {
        while (head != null) {
          document.write(head.data + " ");
          head = head.next;
        }
      }
  
      // Driver Code
      /* Start with the empty list */
      //Node head = null;
  
      /* Use push() to construct below list
      1->2->3->4->5 */
      push(5);
      push(4);
      push(3);
      push(2);
      push(1);
  
      head = reverseList(head);
  
      printList(head);
        
</script>


Output

5 4 3 2 1 

Complexity Analysis:

  • Time Complexity : O(n), as we are traversing over the linked list of size N using a while loop.
  • Auxiliary Space: O(N), as we are using stack of size N in worst case which is extra space.

We can reverse a linked list with O(1) auxiliary space. See more methods to reverse a linked list.



Previous Article
Next Article

Similar Reads

Print Reverse a linked list using Stack
Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive solution to print reverse a linked list. Requires e
9 min read
Reverse a Linked List in groups of given size using Stack
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL and k = 3 Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL. Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL and k = 5 Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-
10 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7&lt; – &gt; 6 &lt; – &gt; 8 &lt; – &gt; 11 &lt; – &gt; 3, K = 3 Output: 8 &lt; – &gt; 6 &lt; – &gt; 7 &lt; – &gt; 3 &lt; – &gt; 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 &lt; – &gt; 6
13 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1, K = 3Output: 7&lt;–&gt;6&lt;–&gt;8&lt;–&gt;1&lt;–&gt;3&lt;–&gt;11 Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1 &lt;–
14 min read
Java Program to Reverse a String using Stack
The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character
2 min read
C Program to Reverse a Stack using Recursion
Write a program to reverse a stack using recursion, without using any loop. Example:  Input: elements present in stack from top to bottom 1 2 3 4 Output: 4 3 2 1  Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1 Recommended PracticeReverse a StackTry It!Reverse a stack using Recursion The idea of the solution is to hold all va
5 min read
C++ Program to Reverse a String Using Stack
Given a string, reverse it using stack. For example "GeeksQuiz" should be converted to "ziuQskeeG". Following is simple algorithm to reverse a string using stack. 1) Create an empty stack.2) One by one push all characters of string to stack.3) One by one pop all characters from stack and put them back to string.Recommended PracticeReverse a string
4 min read
Java Program for Reverse a linked list
Given a pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes. Examples: Input: Head of following linked list 1-&gt;2-&gt;3-&gt;4-&gt;NULLOutput: Linked list should be changed to, 4-&gt;3-&gt;2-&gt;1-&gt;NULL Input: Head of following linked list 1-&gt;2-&gt;3-
3 min read
C Program to reverse each node value in Singly Linked List
A linked list is a linear collection of data elements, in which each node points to the next node. Unlike an array, it doesn't have upper limit and hence extremely useful. The task is to access value of each node of linked list and reverse them. Examples: Input : 56 87 12 49 35 Output : 65 78 21 94 53 Input : 128 87 12433 491 33 Output : 821 78 334
2 min read
C++ Program For Printing Reverse Of A Linked List Without Actually Reversing
Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1-&gt;2-&gt;3-&gt;4, then output should be 4-&gt;3-&gt;2-&gt;1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorithm: printReverse(head) 1. call print reverse for h
2 min read
Practice Tags :