lurenaa的博客

😝实现

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
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {

}

/** Push element x onto stack. */
void push(int x) {
q.push(x);
}

/** Removes the element on top of the stack and returns that element. */
int pop() {
int val;
while(q.size() != 1) {
int x = q.front();
h.push(x);
q.pop();
}
val = q.front();
// h.push(x);
q.pop();
while(h.size()) {
int x = h.front();
h.pop();
q.push(x);
}
return val;
}

/** Get the top element. */
int top() {
int val;
while(q.size() != 1) {
int x = q.front();
h.push(x);
q.pop();
}
val = q.front();
h.push(val);
q.pop();
while(h.size()) {
int x = h.front();
h.pop();
q.push(x);
}
return val;
}

/** Returns whether the stack is empty. */
bool empty() {
return q.size() == 0;
}
private:
queue<int> q, h;
};

Accepted

16/16 cases passed (8 ms)

Your runtime beats 6.14 % of cpp submissions

Your memory usage beats 5.42 % of cpp submissions (9.1 MB)