From 089ac333f2eacbf6bb96f2002ab34f70a2fa6ecd Mon Sep 17 00:00:00 2001 From: ishika22 Date: Sat, 23 Oct 2021 17:50:26 +0530 Subject: [PATCH] Add Reverse Stack (#2653) --- DataStructures/Stacks/ReverseStack.java | 70 +++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 DataStructures/Stacks/ReverseStack.java diff --git a/DataStructures/Stacks/ReverseStack.java b/DataStructures/Stacks/ReverseStack.java new file mode 100644 index 00000000..8db3fb7c --- /dev/null +++ b/DataStructures/Stacks/ReverseStack.java @@ -0,0 +1,70 @@ +package DataStructures.Stacks; + +import java.util.Scanner; +import java.util.Stack; + +/** + * Reversal of a stack using recursion. + * + * @author Ishika Agarwal, 2021 + */ + +public class ReverseStack { + + public static void main(String args[]){ + + Scanner sc = new Scanner(System.in); + System.out.println("Enter the number of elements you wish to insert in the stack"); + int n = sc.nextInt(); + int i; + Stack stack = new Stack(); + System.out.println("Enter the stack elements"); + for(i = 0; i < n ; i++) + stack.push(sc.nextInt()); + sc.close(); + reverseStack(stack); + System.out.println("The reversed stack is:"); + while(!stack.isEmpty()){ + System.out.print(stack.peek()+","); + stack.pop(); + } + + } + + private static void reverseStack(Stack stack) { + if(stack.isEmpty()){ + return; + } + + //Store the topmost element + int element = stack.peek(); + //Remove the topmost element + stack.pop(); + + //Reverse the stack for the leftover elements + reverseStack(stack); + + //Insert the topmost element to the bottom of the stack + insertAtBottom(stack,element); + + } + + private static void insertAtBottom(Stack stack, int element) { + + if(stack.isEmpty()){ + //When stack is empty, insert the element so it will be present at the bottom of the stack + stack.push(element); + return; + } + + int ele = stack.peek(); + /*Keep popping elements till stack becomes empty. Push the elements once the topmost element has + moved to the bottom of the stack. + */ + stack.pop(); + insertAtBottom(stack, element); + + stack.push(ele); + } + +}