两个栈实现队列
问题陈述
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路分析
设计其中一个栈为主栈,另一栈为辅助栈,然后根据队列先进先出的特性,我们需要保持每次入主栈元素放入栈底,这样最先进入的元素位于栈顶,实现了先进先出。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class CQueue { LinkedList<Integer> A, B; public CQueue() { A = new LinkedList<Integer>(); B = new LinkedList<Integer>(); } public void appendTail(int value) { A.addLast(value); } public int deleteHead() { if(!B.isEmpty()) return B.removeLast(); if(A.isEmpty()) return -1; while(!A.isEmpty()) B.addLast(A.removeLast()); return B.removeLast(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public class TwoStack_To_Queue{ Stack<Integer> stack1; Stack<Integer> stack1; int size; public TwoStack_To_Queue(){ stack1=new Stack<Integer>(); stack2=new Stack<Integer>(); size=0; } public void appendTail(int value) { stack1.add(value); }
public int deleteHead() { if (stack2.isEmpty()) { if (stack1.isEmpty()) return -1; while (!stack1.isEmpty()) { stack2.add(stack1.pop()); } return stack2.pop(); } else return stack2.pop(); } public void print(){ while(!stack1.isEmpty()){ System.out.print(stack1.pop()); } } public static void main(String[] args){ TwoStack_To_Queue twoStack_To_Queue=new TwoStack_To_Queue(); twoStack_To_Queue.appendtail(4); twoStack_To_Queue.appendtail(3); twoStack_To_Queue.deleteHead(); twoStack_To_Queue.print(); } }
|