-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse_a_stack_using_recursion.java
80 lines (61 loc) · 1.64 KB
/
Reverse_a_stack_using_recursion.java
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
71
72
73
74
75
76
77
78
79
80
/*
Reverse a stack using recursion
Write a program to reverse a stack using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following ADT functions on Stack S:
isEmpty(S)
push(S)
pop(S)
https://www.cdn.geeksforgeeks.org/reverse-a-stack-using-recursion/
*/
// NOTE: a good code to understand recursion in deep as well
/**
*
* @author shivam
*/
import java.util.Stack;
public class reverse_sort_a_stack_using_recursion {
static Stack<Integer> stack= new Stack<Integer>();
static void insert_at_bottom(int x)
{
if(stack.isEmpty())
{
stack.push(x);
}
else
{
int temp= stack.peek();
stack.pop();
insert_at_bottom(x);
stack.push(temp);
}
}
static void reverse()
{
if(stack.isEmpty()!=true)
{
int a=stack.peek();
stack.pop();
reverse();
insert_at_bottom(a);
}
}
//driver
public static void main(String[] args) {
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("original stack is as follows");
System.out.println(stack);
reverse();
System.out.println("After reverse sort, stack is as follows");
System.out.println(stack);
}
}
/*
run:
original stack is as follows
[1, 2, 3, 4]
After reverse sort, stack is as follows
[4, 3, 2, 1]
BUILD SUCCESSFUL (total time: 0 seconds)
*/