您的位置:首页 > 产品设计 > UI/UE

225 Implement Stack using Queues(用队列实现栈Medium)

2015-06-17 09:36 393 查看
题目意思:用队列实现栈,push(),pop(),top(),empty()

思路:用两个queue,pop时将一个queue的元素pop再push到另一个队列,queue只留最后一个元素,并pop,再将目标队列变为另一个

  ps:用栈实现队列,参考剑指offer

class Stack {
private:
queue<int> q[2];
int flag=0;
public:
// Push element x onto stack.
void push(int x) {
q[flag].push(x);
}

// Removes the element on top of the stack.
void pop() {
while(q[flag].size()>1){
q[1-flag].push(q[flag].front());
q[flag].pop();
}
q[flag].pop();
flag=1-flag;
}

// Get the top element.
int top() {
return q[flag].back();
}

// Return whether the stack is empty.
bool empty() {
if(q[flag].empty()){
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: