您的位置:首页 > 运维架构

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

2017-03-03 09:06 387 查看
主要思路是,一个stack1占用来接收正常的压栈,一个stack2用来存放stack1的倒序,当执行pop()操作时,弹出的是stack2的栈顶元素,就会有“先进先出的效果”。

import java.util.Stack;

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

public void push(int node) {
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
stack1.push(node);
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}

public int pop() {
return stack2.pop();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s = new Solution();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
System.out.println(s.pop());
}

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