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 empty
operations 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).
题意:利用队列实现栈。
方法一:队列为先进先出线性表,栈为先进后出线性表。利用in和out两个队列实现栈。
入栈时:直接进入in队列即可。
出栈时:若in队列不空,则应将in队列中队尾元素出队,即将in队列中的除队尾外所有元素出队并按序加入out队列中,再将队尾元素出队;若in队列为空,则应将out队列中队尾元素出队,将out队列中除队尾元素外所有元素出队并按序加入in队列中,将队尾元素出队。
class MyStack {
public:
queue<int>in,out;
MyStack() {
}
void push(int x) {
in.push(x);
}
int pop() {
int tmp;
if(!in.empty()){
while(in.size()>1){
out.push(in.front());
in.pop();
}
tmp=in.front();
in.pop();
return tmp;
}else {
while(out.size()>1){
in.push(out.front());
out.pop();
}
tmp=out.front();
out.pop();
return tmp;
}
}
int top() {
int tmp=pop();
if(!in.empty())
in.push(tmp);
else
out.push(tmp);
return tmp;
}
bool empty() {
if(in.empty()&&out.empty())
return 1;
else
return 0;
}
};
方法二:使用一个队列实现。在将元素入栈时,将队列中的元素弹出并重新加入队列,并保证新入栈元素处于队首位置。此时栈的出栈,取栈顶元素等操作即为队列的相应操作。
class MyStack {
public:
queue<int>que;
MyStack() {
}
void push(int x) {
que.push(x);
for(int i=0;i<que.size()-1;i++){
que.push(que.front());
que.pop();
}
}
int pop() {
int tmp=que.front();
que.pop();
return tmp;
}
int top() {
return que.front();
}
bool empty() {
if(que.empty())
return 1;
else
return 0;
}
};