Skip to content

Commit 089ac33

Browse files
authored
Add Reverse Stack (TheAlgorithms#2653)
1 parent 5855983 commit 089ac33

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package DataStructures.Stacks;
2+
3+
import java.util.Scanner;
4+
import java.util.Stack;
5+
6+
/**
7+
* Reversal of a stack using recursion.
8+
*
9+
* @author Ishika Agarwal, 2021
10+
*/
11+
12+
public class ReverseStack {
13+
14+
public static void main(String args[]){
15+
16+
Scanner sc = new Scanner(System.in);
17+
System.out.println("Enter the number of elements you wish to insert in the stack");
18+
int n = sc.nextInt();
19+
int i;
20+
Stack<Integer> stack = new Stack<Integer>();
21+
System.out.println("Enter the stack elements");
22+
for(i = 0; i < n ; i++)
23+
stack.push(sc.nextInt());
24+
sc.close();
25+
reverseStack(stack);
26+
System.out.println("The reversed stack is:");
27+
while(!stack.isEmpty()){
28+
System.out.print(stack.peek()+",");
29+
stack.pop();
30+
}
31+
32+
}
33+
34+
private static void reverseStack(Stack<Integer> stack) {
35+
if(stack.isEmpty()){
36+
return;
37+
}
38+
39+
//Store the topmost element
40+
int element = stack.peek();
41+
//Remove the topmost element
42+
stack.pop();
43+
44+
//Reverse the stack for the leftover elements
45+
reverseStack(stack);
46+
47+
//Insert the topmost element to the bottom of the stack
48+
insertAtBottom(stack,element);
49+
50+
}
51+
52+
private static void insertAtBottom(Stack<Integer> stack, int element) {
53+
54+
if(stack.isEmpty()){
55+
//When stack is empty, insert the element so it will be present at the bottom of the stack
56+
stack.push(element);
57+
return;
58+
}
59+
60+
int ele = stack.peek();
61+
/*Keep popping elements till stack becomes empty. Push the elements once the topmost element has
62+
moved to the bottom of the stack.
63+
*/
64+
stack.pop();
65+
insertAtBottom(stack, element);
66+
67+
stack.push(ele);
68+
}
69+
70+
}

0 commit comments

Comments
 (0)