题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) {
//将栈2中的值全部拷入stack1中 while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } stack1.push(node); } public int pop() {
//将栈1中拷入栈二中,输出顺序就是:先进先出 while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } return stack2.pop(); }
方式二:
public void push2(int node) { stack1.push(node);//将数据放入栈1 } public int pop2() { if(stack2.isEmpty()){//若栈二中没有数据,将栈1数据拷入,有则直接输出栈2 //将第一个栈中的值去全部放入第二个栈中 while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } //取出第二个栈的值 return stack2.pop(); }