0%

submission-details

Implement Queue using Stacks – LeetCode 232

Problem

Description

Implement the following operations of a queue using stacks.

  • push(x) – Push element x to the back of queue.

  • pop() – Removes the element from in front of queue.

  • peek() – Get the front element.

  • empty() – Return whether the queue 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
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {

}

/** Push element x to the back of queue. */
void push(int x) {
while(!s1.empty())
{s2.push(s1.top()); s1.pop();}
s1.push(x);
while(!s2.empty())
{s1.push(s2.top()); s2.pop();}
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
int tmp = s1.top();
s1.pop();
return tmp;
}

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

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

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

思路

在push时维护queue的顺序,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$3$ ms,排名$39.44\%$

Better

思路

理论上更好的方案,针对push多的情况,而且pop是严格一倍n,性能理应更强,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$3$ ms,排名$39.44\%$

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

}

/** Push element x to the back of queue. */
void push(int x) {
if(s1.empty())
front = x;
s1.push(x);
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
if(s2.empty()){
while(!s1.empty())
{s2.push(s1.top()); s1.pop();}
}
int tmp = s2.top();
s2.pop();
return tmp;
}

/** Get the front element. */
int peek() {
if(!s2.empty())
return s2.top();
return front;
}

/** Returns whether the queue is empty. */
bool empty() {
return s1.empty() && s2.empty();
}
private:
stack<int> s1, s2;
int front;
};

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