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

LeetCode 232. Implement Queue using Stacks

2016-04-04 20:31 549 查看
和225类似,queue和stack的性质正好相反,因此在push时要进行处理。

维护两个stack:stk和tmp,stk存放与queue相反的顺序,比如queue为:1、4、5,stk为:5、4、1,这样stk.top()会一直等于queue.front()。

每次push进一个数x时,先把stk内的数全push进tmp中,再把x压入stk,最后把tmp中的数全push进stk,这样就保证了x在stk的栈底。

class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
while(!stk.empty()){
tmp.push(stk.top());
stk.pop();
}
stk.push(x);
while(!tmp.empty()){
stk.push(tmp.top());
tmp.pop();
}
}

// Removes the element from in front of queue.
void pop(void) {
stk.pop();
}

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

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