Come from : [https://leetcode-cn.com/problems/implement-stack-using-queues/submissions/]
225. Implement Stack using Queues
1.Question
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.
Notes:
1. You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
2. Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
3. You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Example :
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
2.Answer
easy 类型题目。.不多BB
AC代码如下:
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue<int> temp_queue; //定义一个临时队列,利用该队列进行原始data_queue元素 与新元素的 次序交换
temp_queue.push(x);
while(!data.empty())
{
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 temp = data.front(); //取栈顶元素,相当于取 队列头部元素
data.pop(); //弹出队列头部元素
return temp; //返回栈顶的元素,相当于返回队列的头部元素
}
/** Get the top element. */
int top() {
return data.front(); //获取栈顶元素,等于 返回队列头部元素
}
/** Returns whether the stack is empty. */
bool empty() {
return data.empty();
}
private:
queue<int> data; //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();
*/
3.我的收获
栈,队列。。。
fighting。。。
2019/6/16 胡云层 于南京 101