用两个栈实现一个队列
Posted 梵高先生
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用两个栈实现一个队列相关的知识,希望对你有一定的参考价值。
【题目】两个栈实现一个队列
1 import java.util.Stack; 2 3 public class Main { 4 5 public static void main(String[] args) { 6 7 Stack<Integer> stack1 = new Stack<Integer>(); 8 Stack<Integer> stack2 = new Stack<Integer>(); 9 10 MyQueue myQueue = new MyQueue(stack1, stack2); 11 12 myQueue.appendTail(1); 13 myQueue.appendTail(2); 14 myQueue.appendTail(3); 15 System.out.println(myQueue.deleteHead()); 16 System.out.println(myQueue.deleteHead()); 17 myQueue.appendTail(4); 18 myQueue.appendTail(5); 19 System.out.println(myQueue.deleteHead()); 20 System.out.println(myQueue.deleteHead()); 21 System.out.println(myQueue.deleteHead()); 22 System.out.println(myQueue.deleteHead()); 23 24 } 25 26 } 27 28 class MyQueue { 29 30 private Stack<Integer> stack1; 31 private Stack<Integer> stack2; 32 33 public MyQueue(Stack<Integer> stack1, Stack<Integer> stack2) { 34 this.stack1 = stack1; 35 this.stack2 = stack2; 36 } 37 38 public Boolean appendTail(Integer num) { 39 Boolean result = false; 40 if (null != num) { 41 stack1.push(num); 42 result = true; 43 } 44 return result; 45 } 46 47 public Integer deleteHead() { 48 if (!stack2.isEmpty()) { 49 return stack2.pop(); 50 } 51 52 if (stack2.isEmpty() && !stack1.isEmpty()) { 53 int length = stack1.size(); 54 for (int i = 0; i < length; i++) { 55 Integer temp = stack1.pop(); 56 stack2.push(temp); 57 } 58 return stack2.pop(); 59 } 60 61 return null; 62 } 63 64 public Stack<Integer> getStack1() { 65 return stack1; 66 } 67 68 public void setStack1(Stack<Integer> stack1) { 69 this.stack1 = stack1; 70 } 71 72 public Stack<Integer> getStack2() { 73 return stack2; 74 } 75 76 public void setStack2(Stack<Integer> stack2) { 77 this.stack2 = stack2; 78 } 79 80 }
以上是关于用两个栈实现一个队列的主要内容,如果未能解决你的问题,请参考以下文章