《剑指offer2》问题9 用两个栈实现队列 Java实现

来源:互联网 发布:chm制作软件 编辑:程序博客网 时间:2024/06/04 17:44

题目来源:剑指offer

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:stack1负责插入,stack2负责弹出。当调用淡出时候,讲stack1中的所有元素弹出并压入到stack2,再出栈,这就保证了先进先出。
import java.util.Stack;public class J_TwoSTACKQueue {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node) {        stack1.push(node);    }    public int pop() {        if (stack2.empty()){            while (!stack1.empty()){                int n=stack1.pop();                stack2.push(n);            }        }        if (stack2.empty()){           throw new RuntimeException();        }        return stack2.pop();    }}


原创粉丝点击