使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
- 你只能使用队列的基本操作-- 也就是
push to back,peek/pop from front,size, 和is empty这些操作是合法的。 - 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列, 只要是标准的队列操作即可。
- 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
思路:
实现栈的push()可以直接调用queue的入队操作push(),
可以通过不断将队头元素移到队尾,使得最后入队的元素出现在队头,就可以直接通过queue的pop()或者top()方法来实现栈了。
题解:
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int length = q.size();
int tmp;
for (int i = 0; i < length; i++) {
tmp = q.front();
q.pop();
if (i!=length-1) {
q.push(tmp);
}
}
return tmp;
}
/** Get the top element. */
int top() {
int length = q.size();
int tmp;
for (int i = 0; i < length; i++) {
tmp = q.front();
q.pop();
q.push(tmp);
}
return tmp;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
/**
* 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();
*/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues

被折叠的 条评论
为什么被折叠?



