-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue_Stack.java
75 lines (65 loc) · 1.68 KB
/
Queue_Stack.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
import java.util.Stack;
public class Queue_Stack {
public static class Queue {
//2 stacks
Stack<String> s1 = new Stack<>();
Stack<String> s2 = new Stack<>();
public int curr_size;
Queue()
{
curr_size = 0;
}
void add(String x)
{
curr_size++;
// Push all q1 to q2
while (!s1.isEmpty()) {
s2.push(s1.lastElement());
s1.pop();
}
s1.push(x);
while (!s2.isEmpty()) {
s1.push(s2.lastElement());
s2.pop();
}
}
public void remove()
{
if (s1.isEmpty()) {
return;
}
while (!s1.isEmpty()) {
s2.push(s1.lastElement());
s1.pop();
}
s2.pop();
while (!s2.isEmpty()) {
s1.push(s2.lastElement());
s2.pop();
}
// if no elements are there in q1
curr_size--;
}
public String peek()
{
String result;
if (s1.isEmpty()) {
return "Empty";
}
while (!s1.isEmpty()) {
s2.push(s1.lastElement());
s1.pop();
}
result = s2.lastElement();
while (!s2.isEmpty()) {
s1.push(s2.lastElement());
s2.pop();
}
return result;
}
public int size()
{
return curr_size;
}
}
}