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

LeetCode OJ:Implement Queue using Stacks(栈实现队列)

2016-01-05 22:40 567 查看
比较典型的一个题目,easy,不过可以有许多实现方式。

这里用的方式是每次pop完成之后再将stack2中的内容立即倒回stack1中。但是其他的实现也可以不是这样,可以是需要push的时候检查再,如果内容在stack2中,这时候将其倒回在进行push。这里采取第一种比较笨的方法,代码如下所示:

class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
s1.push(x);
}

// Removes the element from in front of queue.
void pop(void) {
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
s2.pop();
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}

// Get the front element.
int peek(void) {
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
int ret = s2.top();
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
return ret;
}

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