-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement stack using queue
111 lines (88 loc) · 1.94 KB
/
Implement stack using queue
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Implement stack using queue - easy - 07/08/2023
// Approach 1 - two queues - push - O(1), pop O(n)
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2 ;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
private int top;
public void push(int x) {
top = x;
q1.add(x);
}
public int pop() {
while(q1.size() > 1){
top = q1.remove();
q2.add(top);
}
int res = q1.remove();
while(!q2.isEmpty()){
q1.add(q2.remove());
}
return res;
}
public int top() {
return top;
}
public boolean empty() {
return q1.isEmpty();
}
}
// Approach 2 - push O(n), pop O(1)
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2 ;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
private int top;
public void push(int x) {
top = x;
q2.add(x);
while(!q1.isEmpty()){
q2.add(q1.remove());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
int res = q1.remove();
if(!q1.isEmpty()){
top = q1.peek();
}
return res;
}
public int top() {
return top;
}
public boolean empty() {
return q1.isEmpty();
}
}
// Approach 3 - one queue Push O(n), pop O(1)
class MyStack {
Queue<Integer> q;
public MyStack() {
q = new LinkedList<>();
}
public void push(int x) {
q.add(x);
int size = q.size();
while(size-- > 1){
q.add(q.remove());
}
}
public int pop() {
return q.remove();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.isEmpty();
}
}