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

[leetcode]232. Implement Queue using Stacks

2016-10-26 19:38 351 查看
题目链接:https://leetcode.com/problems/implement-queue-using-stacks/

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.

pop() -- Removes the element from in front of queue.

peek() -- Get the front element.

empty() -- Return whether the queue is empty.
class Queue {
private:
stack<int> _old,_new;

public:
void shiftStack()
{
if(_old.empty())
{
while(!_new.empty())
{
_old.push(_new.top());
_new.pop();
}
}
}

void push(int x)
{
_new.push(x);
}

void pop(void)
{
shiftStack();
if(!_old.empty())
_old.pop();
}

int peek(void)
{
shiftStack();
if(!_old.empty())
return _old.top();
return 0;
}

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