forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
75 lines (58 loc) · 1.35 KB
/
main2.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
/// Source : https://leetcode.com/problems/implement-stack-using-queues/description/
/// Author : liuyubobobo
/// Time : 2018-09-29
#include <iostream>
#include <queue>
#include <cassert>
using namespace std;
/// Naive Implementation
/// Using a variable to record top element:)
///
/// Time Complexity: init: O(1)
/// push: O(1)
/// pop: O(n)
/// top: O(1)
/// empty: O(1)
/// Space Complexity: O(n)
class MyStack {
private:
queue<int> q;
int topV;
public:
/** Initialize your data structure here. */
MyStack() {}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
topV = x;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
assert(!empty());
queue<int> q2;
while(q.size() > 1){
q2.push(q.front());
q.pop();
}
int ret = q.front();
q.pop();
while(!q2.empty()){
q.push(q2.front());
topV = q2.front();
q2.pop();
}
return ret;
}
/** Get the top element. */
int top() {
assert(!empty());
return topV;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
int main() {
return 0;
}