Stack

题目描述[原题链接][https://www.acwing.com/problem/content/description/36/]

请用栈实现一个队列,支持如下四种操作:

  • push(x) – 将元素x插到队尾;
  • pop() – 将队首的元素弹出,并返回该元素;
  • peek() – 返回队首元素;
  • empty() – 返回队列是否为空;

注意:

  • 你只能使用栈的标准操作:push to toppeek/pop from top, sizeis empty
  • 如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
  • 输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;

样例

1
2
3
4
5
6
7
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false

算法描述

初始化两个栈,压入操作直接压入第一个栈即可,弹出和取队列首部元素需要将数据转入另一个栈中,操作完后再将数据装回,判空即判断第一个栈是否为空即可,单向队列就可以实现了;

C++代码

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
class MyQueue {
public:
stack<int> sta1;
stack<int> sta2;
/** Initialize your data structure here. */
MyQueue() {

}

/** Push element x to the back of queue. */
void push(int x) {
sta1.push(x);
}

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

/** Get the front element. */
int peek() {
int t;
while(!sta1.empty()){
t = sta1.top();
sta1.pop();
sta2.push(t);
}
t = sta2.top();
while(!sta2.empty()){
sta1.push(sta2.top());
sta2.pop();
}
return t;
}

/** Returns whether the queue is empty. */
bool empty() {
if(sta1.empty())return true;
else false;
}
};

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

Java代码

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 MyQueue {

Stack<Integer> sta1;
Stack<Integer> sta2;

/** Initialize your data structure here. */
public MyQueue() {
sta1 = new Stack<>();
sta2 = new Stack<>();
}

/** Push element x to the back of queue. */
public void push(int x) {
sta1.push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
swap(sta1,sta2);
int e = sta2.pop();
swap(sta2,sta1);
return e;
}

/** Get the front element. */
public int peek() {
swap(sta1,sta2);
int e = sta2.peek();
swap(sta2,sta1);
return e;
}

/** Returns whether the queue is empty. */
public boolean empty() {
return sta1.empty();
}

public void swap(Stack<Integer> s1,Stack<Integer> s2){
while(!s1.empty()){
s2.push(s1.pop());
}
}
}

/**
* 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();
* boolean param_4 = obj.empty();
*/