题目描述
使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
思路
难点:如何实现push(x)操作?
C++代码
//
// Created by YaMiwan on 2020-05-02.
//
#include <iostream>
#include <queue>
using namespace std;
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue<int> temp_queue; // 创建临时队列
temp_queue.push(x); // 先将新元素push进入临时队列
while (!_data.empty()){ // _data.empty()为空时返回TRUE,不为空时返回NULL
temp_queue.push(_data.front()); // 将原数据队列元素导入临时队列
_data.pop();
}
while (!temp_queue.empty()){
_data.push(temp_queue.front()); // 将临时队列元素导入原数据队列
temp_queue.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = _data.front();
_data.pop();
return x;
}
/** Get the top element. */
int top() {
return _data.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return _data.empty();
}
private:
queue<int> _data; // 设为私有
};
/**
* 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();
*/
测试
int main(){
MyStack S;
S.push(1);
S.push(2);
S.push(3);
S.push(4);
printf("%d\n", S.top());
S.pop();
printf("%d\n", S.top());
S.push(5);
printf("%d\n", S.top());
return 0;
}
输出
4
3
5