Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
C Program to reverse the digits of a number using recursion
Next article icon

C Program to Reverse a Stack using Recursion

Last Updated : 26 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 3
Output: 3 2 1

Recommended Practice
Reverse a Stack
Try It!

Reverse a stack using Recursion

The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one at the bottom of the stack. 

Illustration: 

Below is the illustration of the above approach

  • Let given stack be
       1        
       2
       3
       4

    

  • After all calls of reverse,  4 will be passed to function insert at bottom, after that 4 will pushed to the stack when stack is empty

    

        4       
  • Then 3 will be passed to function insert at bottom , it will check if the stack is empty or not if not then pop all the elements back and insert 3 and then push other elements back.
                                                                                               
       4       
       3
  • Then 2 will be passed to function insert at bottom , it will check if the stack is empty or not if not then pop all the elements back and insert 2 and then push other elements back.
      4       
      3
      2
  • Then 1 will be passed to function insert at bottom , it will check if the stack is empty or not if not then pop all the elements back and insert 1 and then push other elements back.
     
      4       
      3
      2
      1

 Follow the steps mentioned below to implement the idea:

  • Create a stack and push all the elements in it.
  • Call reverse(), which will pop all the elements from the stack and pass the popped element to function insert_at_bottom()
  • Whenever insert_at_bottom() is called it will insert the passed element at the bottom of the stack.
  • Print the stack                             

Below is the implementation of the above approach:

C




// C program to reverse a
// stack using recursion
#include <stdio.h>
#include <stdlib.h>
#define bool int
  
// structure of a stack node
struct sNode {
    char data;
    struct sNode* next;
};
  
// Function Prototypes
void push(struct sNode** top_ref, int new_data);
int pop(struct sNode** top_ref);
bool isEmpty(struct sNode* top);
void print(struct sNode* top);
  
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
void insertAtBottom(struct sNode** top_ref, int item)
{
    if (isEmpty(*top_ref))
        push(top_ref, item);
    else {
  
        // Hold all items in Function Call
        // Stack until we reach end of the
        // stack. When the stack becomes
        // empty, the isEmpty(*top_ref)becomes
        // true, the above if part is executed
        // and the item is inserted at the bottom
        int temp = pop(top_ref);
        insertAtBottom(top_ref, item);
  
        // Once the item is inserted
        // at the bottom, push all
        // the items held in Function
        // Call Stack
        push(top_ref, temp);
    }
}
  
// Below is the function that
// reverses the given stack using
// insertAtBottom()
void reverse(struct sNode** top_ref)
{
    if (!isEmpty(*top_ref)) {
        // Hold all items in Function
        // Call Stack until we
        // reach end of the stack
        int temp = pop(top_ref);
        reverse(top_ref);
  
        // Insert all the items (held in
        // Function Call Stack)
        // one by one from the bottom
        // to top. Every item is
        // inserted at the bottom
        insertAtBottom(top_ref, temp);
    }
}
  
// Driver Code
int main()
{
    struct sNode* s = NULL;
    push(&s, 4);
    push(&s, 3);
    push(&s, 2);
    push(&s, 1);
  
    printf("
 Original Stack ");
    print(s);
    reverse(&s);
    printf("
 Reversed Stack ");
    print(s);
    return 0;
}
  
// Function to check if
// the stack is empty
bool isEmpty(struct sNode* top)
{
    return (top == NULL) ? 1 : 0;
}
  
// Function to push an item to stack
void push(struct sNode** top_ref, int new_data)
{
  
    // allocate node
    struct sNode* new_node
        = (struct sNode*)malloc(sizeof(struct sNode));
  
    if (new_node == NULL) {
        printf("Stack overflow 
");
        exit(0);
    }
  
    // put in the data
    new_node->data = new_data;
  
    // link the old list
    // off the new node
    new_node->next = (*top_ref);
  
    // move the head to
    // point to the new node
    (*top_ref) = new_node;
}
  
// Function to pop an item from stack
int pop(struct sNode** top_ref)
{
    char res;
    struct sNode* top;
  
    // If stack is empty then error
    if (*top_ref == NULL) {
        printf("Stack overflow 
");
        exit(0);
    }
    else {
        top = *top_ref;
        res = top->data;
        *top_ref = top->next;
        free(top);
        return res;
    }
}
  
// Function to print a
// linked list
void print(struct sNode* top)
{
    printf("
");
    while (top != NULL) {
        printf(" %d ", top->data);
        top = top->next;
    }
}
 
 
Output
Original Stack  1 2 3 4   Reversed Stack  1 2 3 4 

Time Complexity: O(N2). 
Auxiliary Space: O(N) use of Stack 



Next Article
C Program to reverse the digits of a number using recursion
author
kartik
Improve
Article Tags :
  • C Language
  • C Programs
  • DSA
  • Recursion
  • Stack
  • C Misc Programs
Practice Tags :
  • Recursion
  • Stack

Similar Reads

  • C Program to Reverse a String Using Recursion
    Reversing a string means changing the order of characters in the string so that the last character becomes the first character of the string. In this article, we will learn how to reverse a string using recursion in a C program. The string can be reversed by using two pointers: one at the start and
    1 min read
  • C Program to reverse the digits of a number using recursion
    Given an integer N, the task is to reverse the digits of given integer using recursion. Examples: Input: N = 123Output: 321Explanation:The reverse of the given number is 321. Input: N = 12532Output: 23521Explanation:The reverse of the given number is 23521. Approach: Follow the steps below to solve
    2 min read
  • How to Reverse a String in C?
    In C, a string is a sequence of characters terminated by a null character (\0). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C. Example: Inpu
    2 min read
  • C Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "
    3 min read
  • TCS Coding Practice Question | Reverse a String
    Given a string, the task is to reverse this String using Command Line Arguments. Examples: Input: GeeksOutput: skeeGInput: GeeksForGeeksOutput: skeeGroFskeeG Approach 1: Using another String to store the reverse Since the string is entered as Command line Argument, there is no need for a dedicated i
    4 min read
  • C program to create copy of a singly Linked List using Recursion
    Given a pointer to the head node of a Linked List, the task is to create a copy of the linked list using recursion. Examples:: Input: Head of following linked list1->2->3->4->NULLOutput: Original list: 1 -> 2 -> 3 -> 4 -> NULLDuplicate list: 1 -> 2 -> 3 -> 4 -> NU
    3 min read
  • Stack and Queue C/C++ Programs
    The stack and queue are popular linear data structures with a wide variety of applications. The stack follows LIFO (Last In First Out) principle where the data is inserted and extracted from the same side. On the other hand, the queue follows FIFO (First In First Out) principle, i.e., data is insert
    3 min read
  • TCS Coding Practice Question | Reverse a Number
    Given a number, the task is to reverse this number using Command Line Arguments. Examples: Input: num = 12345Output: 54321Input: num = 786Output: 687 Approach: Since the number is entered as Command line Argument, there is no need for a dedicated input lineExtract the input number from the command l
    4 min read
  • Reverse String in C
    In C, reversing a string means rearranging the characters such that the last character becomes the first, the second-to-last character becomes the second, and so on. In this article, we will learn how to reverse string in C. The most straightforward method to reverse string is by using two pointers
    3 min read
  • Bottom View of a Binary Tree using Recursion
    Given a Binary Tree, the task is to print the bottom view from left to right using Recursion. Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then the latter one in the level traversal is considered. Examples: Example1: The Green nodes represent the bottom view
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences