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

[LeetCode] 232. Implement Queue using Stacks

2017-12-11 20:19 176 查看

232. Implement Queue using Stacks (用两个栈实现一个队列)

Implement Queue using Stacks 用两个栈实现一个队列
题目翻译

解题方法

代码

1. 题目翻译

使用两个栈完成一个队列的下列功能

push(x) – 将x加入队尾。

pop() – 移除队列头部的元素。

peek() – 返回队列头部的元素。

empty() – 如果队列为空返回true。

注意:

只能使用标准的栈操作–包括push,peek,pop,size和empty。

假设所有操作都是有效的(即不存在对空队列的pop和peek操作)。

2. 解题方法

假设我们将元素{1},{2},{3}按序加入队列中,我们可以先按序将这些元素加入栈s1中,这样是没问题的,因为加入栈和队列保持相同的顺序。

但是,当我们要移执行pop的时候,在栈中最先被移除的永远是最后加入的元素,而队列正好相反。所以需要使用两个栈让它们保持相同的顺序。我们需要将s1中的所有元素移入到栈s2中,这时s2中的元素顺序为{3},{2},{1}(1为栈顶),从s2中移出栈顶{1}就相当于移出队列头部。peek操作与pop操作是一样的只不过不用删除s2栈顶只是返回就可以(注意:每次完成后,s1和s2最多只能有一个栈中存在数据,所以当要pop和peek时如果s1非空,则要把s1中元素移动到s2中)。

对于push操作,我们需要在s1中操作,这样才能加入到队尾。同样,操作前需要判断s2如果是非空,需要将s2中的所有数据移动到s1中在进行操作。

3. 代码

//Runtime: 0ms
class MyQueue {
private:
stack<int> s1;
stack<int> s2;
public:
/** Initialize your data structure here. */
MyQueue() {

}

/** Push element x to the back of queue. */
void push(int x) {
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
s1.push(x);
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
int front = 0;
if(!s1.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}

if(!s2.empty()){
front = s2.top();
s2.pop();
}
}else if(!s2.empty()){
front = s2.top();
s2.pop();
}

return front;

}

/** Get the front element. */
int peek() {
int front = 0;
if(!s1.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}

if(!s2.empty()){
front = s2.top();
}
}else if(!s2.empty()){
front = s2.top();
}

return front;
}

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