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

leetcode 232: Implement Queue using Stacks

2015-08-30 15:10 393 查看
Use two stacks. Every time I need to pop, I push all numbers in st1 into st2 except the last one, then I pop that one. After that, I push back all numbers into st1. Don't forget to update the front variable.

class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
if(st1.empty())
front=x;
st1.push(x);
}

// Removes the element from in front of queue.
void pop(void) {
while(st1.size()!=1)
{
st2.push(st1.top());
st1.pop();
}
st1.pop();
if(!st2.empty())
front=st2.top();
while(!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
}

// Get the front element.
int peek(void) {
return front;
}

// Return whether the queue is empty.
bool empty(void) {
return st1.empty();
}
private:
stack<int> st1;
stack<int> st2;
int front;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: