请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾int pop() 从队列的开头移除并返回元素int peek() 返回队列开头的元素boolean empty() 如果队列为空,返回 true ;否则,返回 false说明:
push to top, peek/pop from top, size, 和 is empty 操作是合法的。c++解法
- class MyQueue {
- public:
- MyQueue() {}
-
- void push(int x) {
- st1.push(x);
- }
-
- int pop() {
- auto front = peek();
- st2.pop();
- return front;
- }
-
- int peek() {
- if (st2.empty()) {
- while (!st1.empty()) {
- st2.push(st1.top());
- st1.pop();
- }
- }
- auto cur = st2.top();
- return cur;
- }
-
- bool empty() {
- return st1.empty() && st2.empty();
- }
-
- private:
- stack<int> st1;
- // implement as queue
- stack<int> st2;
- };
栈为先进后出,将事物放入栈中相当于反转一次顺序,放入两次栈即转换为队列,这里使用两个栈来构建队列
本题考察了栈的应用,利用栈反转顺序两次则可得到队列