您的位置:首页 > 其它

两个栈实现一个队列

2016-05-06 10:54 435 查看
题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

1.

class Solution
{
public:
void push(int node) {
//入队时,将元素压入s1。
//出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。
//这个思路,避免了反复“倒”栈,仅在需要时才“倒”一次。
stack1.push(node)    ;
}

int pop() {
int tmp;
if(stack2.empty()){
while(stack1.empty()!=1){
tmp=stack1.top(); //stack1.pop()   删除栈顶元素但不返回其值
stack1.pop();
stack2.push(tmp);
}
}
tmp=stack2.top();
stack2.pop();
return tmp; //返回队首元素

}
private:
stack<int> stack1;
stack<int> stack2;
};


2.

import java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);

}

public int pop() {
int tmp;
if(stack2.isEmpty()){
while(stack1.isEmpty()!=true){
tmp=stack1.peek();
stack1.pop();
stack2.push(tmp);
}
}
tmp=stack2.peek();
stack2.pop();

return tmp;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: