# Reverse a Stack Using Recursion Leetcode

## Introduction

Reversing a stack is one of the most basic coding questions in stacks. In this web log, we are going to discuss the various methods to reverse the stack. Let’s get started.

### Trouble Statement for Reversing a Stack:

Write a program to insert elements to the stack and display the reversed stack.

## Stack

Stack
is a
linear information construction
similar to arrays and linked lists that allow usa to store and retrieve data sequentially. In general, insertion operation is called
“push,”
and deletion operation is called
“pop.”
They are useful when dynamic addition and deletion of elements are required.

At any given time, one tin only admission the top element of a stack. Due to this reason, it is a
LIFO (Concluding In First Out) information construction. In this, the element added last is accessed outset. The time complexity for all operations in a stack is
O(ane), making it efficient and improving performance.

Bank check out

Stack Notes

to learn stack in detail.

### Commuter lawmaking(Main function):

Let’due south check out the main part before moving to each approach. In the primary function, we initialize the stack, enter elements, opposite the stack past calling reverseStack() function and print the reversed stack.

### Main function forDriver lawmaking:

```public static void main(Cord args[]) {   // initialize stack   Stack<Integer> s = new Stack<Integer>();   // button elements   s.button(one);  s.push(ii);   due south.push(3);   southward.button(4);     // print elements before reversing   Organization.out.println("Stack earlier reversing:");   System.out.println(s);     // contrary stack using reverseStack()   southward = reverseStack(due south); // using stacks   reverseStack() // recursion     // impress elements afterwards reversing   Organization.out.println("Stack afterwards reversing:");   System.out.println(south); }
```

At present let’due south go through each approach.

## Reversing a Stack using Another Stack

In this approach, we would be using
an extra stack
to reverse the stack. Let’south encounter the pseudo-code for this arroyo.

### Pseudo – Code for reverseStack()

```initialize an empty extra stack gear up north to the size of the original stack for i to northward   prepare the variable element to the topmost element of the original stack   pop the topmost chemical element of the original stack   button this element into the extra stack render the extra stack, which is reversed
```

### reverseStack()

``` // function to reverse stack using another stack  static Stack<Integer> reverseStack(Stack<Integer> s) {    // initialize extra stack    Stack<Integer> extraStack = new Stack<Integer>();    int n = s.size();      for (int i = 0; i < n; i++) {      // access the acme element      int element = s.peek();      // remove the top element      due south.pop();      // push the chemical element into the extra stack      extraStack.push(element);    }      // return the extraStack which is reversed    return extraStack; }
```

Time Complexity:
O(N)

Popular:   Big Bang Theory Season 12 Wiki

Reason: The loop runs for n times and the fourth dimension complexity for all the stack operations is O(i). Therefore the overall time complexity is O(N)

Space Complexity:
O(Northward)

Reason: An extra stack of size Due north is used.

## Reversing a Stack using 2 Stacks

In this approach, we would be using
two stacks

to reverse the stack. This is similar to the above approach; the departure is that in this arroyo, instead of returning the actress stack, we directly use the original stack later transferring elements. Let’southward meet the pseudo-code for this arroyo.

### Pseudo – Lawmaking for reverseStack()

```initialize two empty stacks, a and b transfer elements from s to a transfer elements from a to b transfer elements from b to s brandish elements of s
```

### Pseudo – Code for transfer

```While stack is non empty  Set element to the topmost element of the s1 stack  Push button element into the s2 stack  Pop chemical element from the s1 stack
```

### transfer()

```// office to transfer elements static void transfer(Stack<Integer> s1, Stack<Integer> s2) {  while (!s1.empty()) {     int chemical element = s1.peek();     s2.push(element);     s1.popular();   }  }
```

### reverseStack()

```// function to reverse stack static Stack<Integer> reverseStack(Stack<Integer> s) {   // initialize stack a and b   Stack<Integer> a = new Stack<Integer>();   Stack<Integer> b = new Stack<Integer>();     // transfer elements from s to a   transfer(due south,a);   // transfer elements from a to b   transfer(a,b);   // transfer elements from b to s   transfer(b,s);   // return the original stack   return s; }
```

Fourth dimension Complexity:
O(N)

Reason: The loop runs for 3n times and the time complexity for all the stack operations is O(1). Therefore the overall time complication is O(Due north)

Infinite Complexity:
O(N)

Reason: Two extra stacks of size Northward is used and the overall space complexity becomes O(N)

## Reversing a Stack using Recursion

If the question specifies that no other information structure can be used to solve the problem,
recursion
has to be used. In this approach, we pop the height chemical element from the given stack and recursively call another instance of the same function. When this child function returns to the parent function, append the popped element to the bottom of the stack. For this, we would be using two recursive functions: reverseStack() and insertAtBottom().

### reverseStack():

Information technology checks if the stack is empty or not. The elevation element is popped out and stored in the chemical element variable if the stack is not empty. We then call reverseStack() office again on the updated stack. When this child function returns, nosotros call the helper function insertAtBottom().

Popular:   Do All Legends Run the Same Speed in Apex

### insertAtBottom():

It recursively inserts an element at the bottom of a stack. If the stack is empty, information technology simply pushes the element else; the summit element is popped out and stored in the topElement variable. Then insertAtBottom() is chosen again on the updated stack. When this child part returns, information technology pushes the topElement back in the stack.

In this solution, we would be using recursion so check out this web log

Recursion in Information Construction: How Does information technology Work, Types & When Used

to know more most recursion.

### reverseStack()

```specify the base example   when the stack is empty, render set up chemical element to topmost element of the stack pop the topmost chemical element of the stack recursively call reverseStack on the updated stack insert the element at the bottom of the stack
```

### insertAtBottom()

```specify the base case    when the stack is empty, push button element to stack and return prepare toElement to topmost chemical element of the stack pop the topmost element of the stack recursively phone call insertAtBottom on the updated stack push element to stack
```

### reverseStack()

```// part to reverse stack using recursion  static void reverseStack(Stack<Integer> s) {    // base of operations case    if(s.empty()) {      return;    }      // access the top chemical element    int element = southward.peek();    // remove the superlative chemical element    south.pop();    // reverse the remaining elements of a stack    reverseStack(southward);    // insert the popped out element at the lesser    insertAtBottom(s,element);  }
```

### insertAtBottom()

`// office to insert top element at the bottom of stack  static void insertAtBottom(Stack<Integer> s, int chemical element) {    // base case    if(due south.empty()) {      // push the element at lesser      s.push(chemical element);      return;    }    // access the acme element    int topElement = s.peek();    // remove the elevation chemical element    s.popular();    // insert the element at the bottom of the stack    insertAtBottom(s,chemical element);    // add the meridian chemical element to the stack    s.button(topElement);  }`

Fourth dimension Complexity:
O(N²)

Two recursive functions are there in which the first function is calling itself recursively and the 2d part in each call. Also, the second office is recursively called.

Infinite Complexity:
O(N)

The recursive plan uses a retentivity of O(Due north) to shop the function call stack.

Popular:   What Does Your League Main Says About You

## Reversing a Stack without using Recursion

In this solution, nosotros would be implementing Implement Stack using Linked Listing and opposite the linked list to get the reversed stack.

Delight endeavor to

implement a Stack using a Linked List

on CodeStudio. Besides, check out this blog,

How To Primary Linked Listing And Its Importance

, and notes on

Time Complexity:
O(N)

Reason: O(N) is the time complexity to reverse a linked list.

Space Complexity:
O(1)

Reason: No extra space is required.

## Frequently Asked Questions

Why is the space complication in recursive solution O(Due north) even though no actress data structure is used?

The recursive program uses a memory of O(N) to store the function call stack. In the recursive program, we are storing both the functions in the call stack i subsequently another.

Why is the time complexity in a recursive solution O(Northward²)?

For each topmost element of the stack, the whole stack is popped out and the topmost element is placed at the bottom of the stack. This takes O(Due north) complexity and doing this for every stack element makes the overall fourth dimension complexity O(Northward²).

How is the topmost stack element inserted at the top chemical element at the bottom of the stack in the recursive approach?

The top element of the stack is popped out and stored in the phone call stack frame until the stack becomes empty. When the stack becomes empty, the top element is added to the empty stack, and all the elements stored in the phone call stack are pushed while returning down the recursion tree.

Can the stack be reversed without using any extra space?

es, if the linked list is used to implement the stack, information technology can be reversed without extra space and linear time complexity.

Which node is considered as the top of the stack in the linked list implementation of the stack?

The head node (or the first node) is considered the meridian element when a stack is implemented using a linked list.

## Central Takeaways

This blog covered the various methods of reversing a stack. The methods involved: reversing a stack using another stack, reversing a stack using two stacks,  reversing a stack using recursion, and reversing a stack using Linked List.
Don’t finish here. Check out our
Data Structures and Algorithms -guided path
to learning DSA from scratch. We hope you lot plant this blog useful. Feel free to comment down below if you accept a meliorate insight into the above approach.

Source: https://www.codingninjas.com/blog/2021/08/24/reversing-a-stack/