-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP14.java
More file actions
90 lines (72 loc) · 2.02 KB
/
P14.java
File metadata and controls
90 lines (72 loc) · 2.02 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package stack_and_queue;
// Java code to reverse a
// stack using recursion
import java.util.Stack;
public class P14 {
// using Stack class for
// stack implementation
static Stack<Character> st = new Stack<>();
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
static void insert_at_bottom(char x)
{
if(st.isEmpty())
st.push(x);
else
{
// All items are held in Function
// Call Stack until we reach end
// of the stack. When the stack becomes
// empty, the st.size() becomes 0, the
// above if part is executed and
// the item is inserted at the bottom
char a = st.peek();
st.pop();
insert_at_bottom(x);
// push all the items held
// in Function Call Stack
// once the item is inserted
// at the bottom
st.push(a);
}
}
// Below is the function that
// reverses the given stack using
// insert_at_bottom()
static void reverse()
{
if(st.size() > 0)
{
// Hold all items in Function
// Call Stack until we
// reach end of the stack
char x = st.peek();
st.pop();
reverse();
// Insert all the items held
// in Function Call Stack
// one by one from the bottom
// to top. Every item is
// inserted at the bottom
insert_at_bottom(x);
}
}
// Driver Code
public static void main(String[] args)
{
// push elements into
// the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
System.out.println("Original Stack");
System.out.println(st);
// function to reverse
// the stack
reverse();
System.out.println("Reversed Stack");
System.out.println(st);
}
}