栈和队列——栈和队列相互实现
如何仅用栈结构实现队列结构?
解:准备两个栈,一个stackIn 一个stackOut,stackIn用来接收入队的元素,stackOut用来进行出队列的操作,当stackOut为空时,从stackIn处弹入(全部)即可
public class StackToQueue{ private Stack<Integer> stackIn; private Stack<Integer> stackOut; public StackToQueue() { stackIn = new Stack<>(); stackOut = new Stack<>(); } public void offer(int num){ stackIn.push(num); } public int poll(){ if(stackOut.empty() && stackIn.empty()){ throw new RuntimeException( "queue is empty" ); } if(stackOut.empty()){ while(!stackIn.empty()){ stackOut.push(stackIn.pop()); } } return stackOut.pop(); } public int peek(){ if(stackOut.empty() && stackIn.empty()){ throw new RuntimeException( "queue is empty" ); } if(stackOut.empty()){ while(!stackIn.empty()){ stackOut.push( stackIn.pop() ); } } return stackOut.peek(); } public boolean empty(){ if(stackOut.empty() && stackIn.empty()) return false; return true; } }
如何仅用队列结构实现栈结构?
解:准备两个队列Queue<Integer> queue = new LinkedList<>(),和help,
queue负责压入栈中的数值,当要pop()弹出数据时,将queue中的数据全部出队列到help,只剩下最后一个即可,peek也是,最后交换queue和help两个Queue指向的队列即可
public class QueueToStack{ private Queue<Integer> queue; private Queue<Integer> help; public QueueToStack() { this.queue = new LinkedList<>(); this.help = new LinkedList<>(); } public void push(int num){ queue.offer(num); } public int pop(){ if(queue.isEmpty()){ throw new RuntimeException( "stack is empty" ); } while(queue.size() > 1){ help.offer(queue.poll()); } //此时queue.poll()之后,queue为空 int num = queue.poll(); swap(queue, help); return num; } public int peek(){ if(queue.isEmpty()){ throw new RuntimeException( "stack is empty" ); } while(queue.size() > 1){ help.offer(queue.poll()); } int num = queue.poll(); help.offer(num); swap(queue, help); return num; } public boolean empty(){ if(queue.isEmpty()) return true; return false; } public void swap(Queue<Integer> q1, Queue<Integer> q2){ Queue<Integer> temp = q1; q1 = q2; q2 = temp; } }