forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
implement-stack-using-queues.cpp
66 lines (55 loc) · 1.24 KB
/
implement-stack-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
// Time: push: O(n), pop: O(1), top: O(1)
// Space: O(n)
class Stack {
public:
queue<int> q_;
// Push element x onto stack.
void push(int x) { // O(n)
q_.emplace(x);
for (int i = 0; i < q_.size() - 1; ++i) {
q_.emplace(q_.front());
q_.pop();
}
}
// Remove the element on top of the stack.
void pop() { // O(1)
q_.pop();
}
// Get the top element.
int top() { // O(1)
return q_.front();
}
// Return whether the stack is empty.
bool empty() { // O(1)
return q_.empty();
}
};
// Time: push: O(1), pop: O(n), top: O(1)
// Space: O(n)
class Stack2 {
public:
queue<int> q_;
int top_;
// Push element x onto stack.
void push(int x) { // O(1)
q_.emplace(x);
top_ = x;
}
// Remove the element on top of the stack.
void pop() { // O(n)
for (int i = 0; i < q_.size() - 1; ++i) {
top_ = q_.front();
q_.emplace(top_);
q_.pop();
}
q_.pop();
}
// Get the top element.
int top() { // O(1)
return top_;
}
// Return whether the stack is empty.
bool empty() { // O(1)
return q_.empty();
}
};