
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题解一:
//stack2有元素就pop,没有元素就将stack1中所有元素倒进来再pop public static void push(int node) { stack1.push(node); } public static int pop() { if(stack1.isEmpty()&&stack2.isEmpty()){ throw new RuntimeException("Queue is empty!"); } if(stack2.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); }
题解二:
//每次psuh是时先将stack2清空放入stck1(保证选入的一定在栈底),stack2始终是用来删除的 //在pop前,先将stack1中中的数据清空放入stack2(保存后入的在栈底),stack1始终用于push public static void push01(int node) { while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } stack1.push(node); } public static int pop01() { while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } return stack2.pop(); }
测试:
public static void main(String[] args) { String[] order={"PUSH_1","PUSH_2","PUSH_3","POP","POP","PUSH_4","POP","PUSH_5","POP","POP"}; for(int i=0;i<order.length;i++){ String s = order[i].toString(); String[] strings = s.split("_"); if(strings[0].equals("PUSH")){ int parseInt = Integer.parseInt(strings[1]); push(parseInt); } if(strings[0].equals("POP")){ int pop = pop(); System.out.print(pop+" "); } } } 输出:1 2 3 4 5