题目描述:
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.
Example:
MyStack stack = new MyStack(); stack.push(1); stack.push(2); stack.top(); // returns 2 stack.pop(); // returns 2 stack.empty(); // returns false
Notes:
- You must use only standard operations of a queue -- which means only
push to back,peek/pop from front,size, andis emptyoperations are valid. - 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.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
class MyStack {
public:
/** Initialize your data structure here. */
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 n=q.size();
for(int i=0;i<n-1;i++)
{
int x=q.front();
q.pop();
q.push(x);
}
int x=q.front();
q.pop();
return x;
}
/** Get the top element. */
int top() {
int n=q.size();
for(int i=0;i<n-1;i++)
{
int x=q.front();
q.pop();
q.push(x);
}
int x=q.front();
q.pop();
q.push(x);
return x;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
本文介绍了一种使用队列来实现栈数据结构的方法。通过详细解释如何进行push、pop、top和empty操作,展示了如何在不支持栈的环境中模拟栈的行为。文章提供了完整的代码示例,包括初始化、元素入栈、出栈、获取栈顶元素和判断栈是否为空等关键操作。
286

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



