forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
70 lines (54 loc) · 1.81 KB
/
ReverseStack.java
File metadata and controls
70 lines (54 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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<Integer> stack = new Stack<Integer>();
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<Integer> 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<Integer> 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);
}
}