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

来源:互联网 发布:python for 编辑:程序博客网 时间:2024/05/13 15:04
思路:有两个栈,栈1和栈2.当入栈的时候,我们将它全放进栈1中,当需要出栈的时候,我们将栈1出栈到栈2中,然后再将栈2依次出栈。出完栈之后,再把stack2中的数pop出push到stack1,接受下次的操作。所以入栈的时候,思路很简单,注意到要将int类型转为Integer类型,我们使用了new Integer(int);当需要出栈的时候,我们用API提供的方法while(stack1.isEmpty())来将所有栈1的元素压入栈2中,然后将栈2弹出就可以。这里又涉及到将Integer的类型转为int类型的方法Integer.intValue();
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(new Integer(node));}public int pop() {int pop;while (!stack1.isEmpty()) {stack2.push(stack1.pop());}pop=stack2.pop().intValue();while(!stack2.isEmpty()){stack1.push(stack2.pop());}return pop;}}

1 0