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

LeetCode || Implement Stack using Queues

2015-07-12 11:35 381 查看
class Stack {
public:
// Push element x onto stack.
void push(int x) {
q1.push(x);
}

// Removes the element on top of the stack.
void pop() {
if(q1.size() == 0)
{
while(q2.size() > 1)
{
q1.push(q2.front());
q2.pop();
}

q2.pop();
}
else
{
while(q1.size() > 1)
{
q2.push(q1.front());
q1.pop();
}

q1.pop();
}
}

// Get the top element.
int top() {
if(q1.size() == 0)
{
while(q2.size() > 1)
{
q1.push(q2.front());
q2.pop();
}

int top = q2.front();
q1.push(top);
q2.pop();
return top;
}
else
{
while(q1.size() > 1)
{
q2.push(q1.front());
q1.pop();
}
int top = q1.front();
q2.push(top);
q1.pop();
return top;
}
}

// Return whether the stack is empty.
bool empty() {
if(q1.size() == 0 && q2.size() == 0)
return true;
return false;
}

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