一、两个栈实现一个队列java
import java.util.Stack; public class TwoStackToQueue { Stack<Integer>s1 = new Stack<Integer>(); Stack<Integer>s2 = new Stack<Integer>(); public void push(int node){ s1.push(node); } public int pop(){ if(s2.isEmpty()){ while(!s1.isEmpty()){ s2.push(s1.pop()); } } return s2.pop(); } public static void main(String[] args) { TwoStackToQueue tsq = new TwoStackToQueue(); tsq.push(1); tsq.push(2); tsq.push(3); System.out.println(tsq.pop()); System.out.println(tsq.pop()); tsq.push(4); tsq.push(5); System.out.println(tsq.pop()); System.out.println(tsq.pop()); } }
二、两个队列实现一个栈node
import java.util.LinkedList; import java.util.Queue; public class TwoQueueToStack { Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); public void push(int node){//添加元素,若是q1不为空,向q1添加;若是q2不为空,向q2添加;都为空时,向q1添加 if(!q1.isEmpty()){ q1.offer(node); }else if(!q2.isEmpty()){ q2.offer(node); }else{ q1.offer(node); } } public int pop(){ if(q1.isEmpty()&&q2.isEmpty()){ try{ throw new RuntimeException("Stcak is Empty!!!"); }catch(Exception e){ } } //若是Q1为空,q2有元素,将q2中的元素依次出队添加到q1,保留最后一个元素,而后出栈。 if(q1.isEmpty()){ while(q2.size()>1){ q1.offer(q2.poll()); } return q2.poll(); } //若是Q2为空,q1有元素,将q1中的元素依次出队添加到q2,保留最后一个元素,而后出栈。 if(q2.isEmpty()){ while(q1.size()>1){ q2.offer(q1.poll()); } return q1.poll(); } return (Integer) null; } public static void main(String[] args) { TwoQueueToStack tqs = new TwoQueueToStack(); tqs.push(1); System.out.println(tqs.pop()); tqs.push(2); tqs.push(3); System.out.println(tqs.pop()); System.out.println(tqs.pop()); } }