0%

implement-stack-using-queues

Implement Stack using Queues – LeetCode 225

Problem

Description

Implement the following operations of a stack using queues.

  • push(x) – Push element x onto stack.

  • pop() – Removes the element on top of the stack.

  • top() – Get the top element.

  • empty() – Return whether the stack is empty.

Answer

Original

Code

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

}

/** Push element x onto stack. */
void push(int x) {
q.push(x);
for(unsigned i = 0; i != q.size() - 1; ++i){
int tmp = q.front();
q.pop();
q.push(tmp);
}
}

/** Removes the element on top of the stack and returns that element. */
int pop() {
int tmp = q.front();
q.pop();
return tmp;
}

/** Get the top element. */
int top() {
return q.front();
}

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

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/

思路

送分题。
耗时$3$ ms,排名$39.86\%$

Better

思路

针对push操作优化,使用两个queue。
耗时$3$ ms,排名$39.86\%$

Code

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
class MyStack {
int curr_size;
queue<int> q1,q2;
public:
/** Initialize your data structure here. */
MyStack() {
curr_size =0;
}

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

/** Removes the element on top of the stack and returns that element. */
int pop() {
if(q1.empty())
return -1;
while(q1.size()!=1){
q2.push(q1.front());
q1.pop();
}
int temp = q1.front();
q1.pop();
curr_size--;

queue<int> q = q1;
q1 = q2;
q2 = q;
return temp;
}

/** Get the top element. */
int top() {
return q1.back();
}

/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
};

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/