能够相互转化原因:除了数组和链表外 其他的数据结构都是对数组和链表的改进;(二维数组是对一维数组的改进)
因此实现一个 先进后出的数组 就是栈 ,一个先进先出的数组就是队列
1.两个栈实现一个队列
public class StackQueue {private Stack<Integer> stack1=new Stack<>();private Stack<Integer> stack2=new Stack<>();public void add(int value) {stack1.push(value);}public void get() {if(!stack2.empty()) {System.out.println(stack2.pop());}else {while(!stack1.empty()) {stack2.push(stack1.pop());}if(!stack2.empty()) {System.out.println(stack2.pop());}}}}
2.两个队列实现一个栈
public class QueueStack {private Queue<Integer> queue1 = new LinkedList<>();private Queue<Integer> queue2 = new LinkedList<>();public void add(Integer value){queue1.offer(value);}Integer data = null;public void get(){while (!queue1.isEmpty()){data = queue1.poll(); if(queue1.isEmpty()){break;}queue2.offer(data);}System.out.println(data); while (!queue2.isEmpty()){queue1.offer(queue2.poll());}}
}