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

queue 模拟 stack

2016-08-18 11:52 337 查看
class Stack {
public:
// Push element x onto stack.
queue<int>A;
queue<int>B;
void push(int x) {
A.push(x);
}

// Removes the element on top of the stack.
void pop() {
while(B.size()){
B.pop();
}
int ans;
while(A.size()){
int t=A.front();
A.pop();
if(A.size()){
B.push(t);
}

}
while(B.size()){
A.push(B.front());
B.pop();

}
}

// Get the top element.
int top() {
while(B.size()){
B.pop();
}
int ans;
while(A.size()){
int t=A.front();
A.pop();
if(!A.size())
ans=t;
B.push(t);

}
while(B.size()){
A.push(B.front());
B.pop();

}
return ans;
}

// Return whether the stack is empty.
bool empty() {
return A.size()==0;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: