用栈实现队列;用队列实现栈;
1 package my_basic; 2 3 import java.util.LinkedList; 4 import java.util.Queue; 5 import java.util.Stack; 6 7 public class StackAndQueueConvert { 8 9 /*利用栈结构实现队列结构*/ 10 public static class Stack2Queue{ 11 private Stack<Integer> stackPush; 12 private Stack<Integer> stackPop; 13 14 public Stack2Queue() { 15 this.stackPush = new Stack<Integer>(); 16 this.stackPop = new Stack<Integer>(); 17 } 18 19 public void push(int num) { 20 stackPush.push(num); 21 } 22 public int peek() { 23 if (stackPush.empty() && stackPop.empty()) { 24 throw new RuntimeException("Queue is empty!"); 25 } 26 daoData(); 27 return stackPop.peek(); 28 } 29 public int poll() { 30 if (stackPush.empty() && stackPop.empty()) { 31 throw new RuntimeException("Queue is empty!"); 32 } 33 daoData(); 34 return stackPop.pop(); 35 } 36 37 public void daoData() { 38 if (!stackPop.isEmpty()) { //原则1: 一定要pop栈 空 才可以倒数据 39 return; 40 } 41 while (!stackPush.isEmpty()) { //原则2:倒数据一定要倒完 42 stackPop.push(stackPush.pop()); 43 } 44 } 45 } 46 47 /*利用队列结构实现栈结构*/ 48 public static class Queue2Stack{ 49 public Queue<Integer> data; 50 public Queue<Integer> help; 51 52 public Queue2Stack() { 53 data = new LinkedList<>(); 54 help = new LinkedList<>(); 55 } 56 57 public void push(int num) { 58 data.add(num); 59 } 60 public int peek() { 61 if (data.isEmpty()) { 62 throw new RuntimeException("stack is empty!"); 63 } 64 while (data.size() > 1) { 65 help.add(data.poll()); 66 } 67 int res = data.poll(); 68 help.add(res); 69 swap(); 70 return res; 71 } 72 73 74 public int poll() { 75 if (data.isEmpty()) { 76 throw new RuntimeException("stack is empty!"); 77 } 78 while (data.size() > 1) { 79 help.add(data.poll()); 80 } 81 int res = data.poll(); 82 swap(); 83 return res; 84 } 85 86 private void swap() { 87 Queue<Integer> tmp = help; 88 help = data; 89 data = tmp; 90 } 91 92 } 93 94 public static void main(String[] args) { 95 Queue2Stack qStack = new Queue2Stack(); 96 qStack.push(1); 97 qStack.push(2); 98 qStack.push(3); 99 100 while (!qStack.data.isEmpty()) { 101 System.out.println(qStack.poll()); 102 } 103 104 //stack2queue 105 Stack2Queue squeue = new Stack2Queue(); 106 squeue.push(1); 107 squeue.push(2); 108 squeue.push(3); 109 int res = squeue.poll(); 110 System.out.println(res); 111 squeue.push(4); 112 res = squeue.poll(); 113 System.out.println(res); 114 } 115 116 } 117