-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path225. Implement Stacks using Queues.cpp
94 lines (71 loc) · 1.47 KB
/
225. Implement Stacks using Queues.cpp
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
class Stack {
queue<int> q1;
queue<int> q2;
public:
// Push element x onto stack.
void push(int x) {
q1.push(x);
}
// Removes the element on top of the stack.
void pop() {
while(q1.size() > 1) {
int e = q1.front();
q1.pop();
q2.push(e);
}
if (!q1.empty())
q1.pop();
queue<int> temp = q1;
q1 = q2;
q2 = temp;
}
// Get the top element.
int top() {
int e;
while(!q1.empty()) {
e = q1.front();
q1.pop();
q2.push(e);
}
queue<int> temp = q1;
q1 = q2;
q2 = temp;
return e;
}
// Return whether the stack is empty.
bool empty() {
return q1.empty() && q2.empty();
}
};
-------
// Better solution
//
// 1 queue solution with O(n) for push and O(1) for every other operation
class Stack {
queue<int> q;
public:
// Push element x onto stack.
void push(int x) {
q.push(x);
int s = q.size();
while(s > 1) {
int e = q.front();
q.pop();
q.push(e);
s--;
}
}
// Removes the element on top of the stack.
void pop() {
if (!q.empty())
q.pop();
}
// Get the top element.
int top() {
return q.front();
}
// Return whether the stack is empty.
bool empty() {
return q.empty();
}
};