用队列实现栈
1 import java.util.ArrayDeque; 2 import java.util.Queue; 3 4 public class StackByQueue { 5 private Queue<Integer> inQueue; 6 private Queue<Integer> outQueue; 7 private Queue<Integer> tempQueue = null; 8 9 /** 10 * Initialize your data structure here. 11 */ 12 public StackByQueue() { 13 this.inQueue = new ArrayDeque<>(); 14 this.outQueue = new ArrayDeque<>(); 15 } 16 17 18 /** 19 * Push element x onto stack. 20 */ 21 public void push(int x) { 22 inQueue.offer(x); 23 while (!outQueue.isEmpty()) { 24 inQueue.offer(outQueue.poll()); 25 } 26 tempQueue = inQueue; 27 inQueue = outQueue; 28 outQueue = tempQueue; 29 30 } 31 32 /** 33 * Removes the element on top of the stack and returns that element. 34 */ 35 public int pop() { 36 return outQueue.poll(); 37 } 38 39 /** 40 * Get the top element. 41 */ 42 public int top() { 43 return outQueue.peek(); 44 } 45 46 /** 47 * Returns whether the stack is empty. 48 */ 49 public boolean empty() { 50 return outQueue.isEmpty(); 51 } 52 53 54 public static void main(String[] args) { 55 StackByQueue obj = new StackByQueue(); 56 obj.push(1); 57 obj.push(2); 58 59 int param_2 = obj.pop(); 60 int param_3 = obj.top(); 61 boolean param_4 = obj.empty(); 62 } 63 64 }