Skip to content

Commit 80c31a2

Browse files
committed
Runtime: 3 ms (Top 41.4%) | Memory: 7.10 MB (Top 85.79%)
1 parent aea6a2e commit 80c31a2

File tree

1 file changed

+21
-46
lines changed

1 file changed

+21
-46
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,38 @@
1-
// Runtime: 8 ms (Top 6.60%) | Memory: 7 MB (Top 20.63%)
1+
// Runtime: 3 ms (Top 41.4%) | Memory: 7.10 MB (Top 85.79%)
2+
23
class MyStack {
34
public:
5+
/** Initialize your data structure here. */
46
queue<int> q1;
5-
queue<int> q2;
67
MyStack() {
7-
8+
89
}
9-
10+
11+
/** Push element x onto stack. */
1012
void push(int x) {
13+
int sz = q1.size();
1114
q1.push(x);
12-
}
13-
14-
int pop() {
15-
16-
while(q1.size() !=1){
17-
int temp = q1.front();
15+
while(sz--){
16+
q1.push(q1.front());
1817
q1.pop();
19-
q2.push(temp);
2018
}
21-
int temp = q1.front();
19+
}
20+
21+
/** Removes the element on top of the stack and returns that element. */
22+
int pop() {
23+
int result = top();
2224
q1.pop();
23-
while(!q2.empty()){
24-
int tp = q2.front();
25-
q2.pop();
26-
q1.push(tp);
27-
}
28-
return temp;
25+
return result;
2926
}
30-
27+
28+
/** Get the top element. */
3129
int top() {
32-
while(q1.size() !=1){
33-
int temp = q1.front();
34-
q1.pop();
35-
q2.push(temp);
36-
}
37-
int temp = q1.front();
38-
q1.pop();
39-
q2.push(temp);
40-
while(!q2.empty()){
41-
int tp = q2.front();
42-
q2.pop();
43-
q1.push(tp);
44-
}
45-
return temp;
30+
return q1.front();
4631
}
47-
32+
33+
/** Returns whether the stack is empty. */
4834
bool empty() {
49-
if(q1.empty()){
50-
return true;
51-
}
52-
return false;
35+
return q1.empty();
5336
}
5437
};
5538

56-
/**
57-
* Your MyStack object will be instantiated and called as such:
58-
* MyStack* obj = new MyStack();
59-
* obj->push(x);
60-
* int param_2 = obj->pop();
61-
* int param_3 = obj->top();
62-
* bool param_4 = obj->empty();
63-
*/

0 commit comments

Comments
 (0)