225. Implement Stack using Queues
1 class MyStack { 2 Queue<Integer> queue; 3 4 /** Initialize your data structure here. */ 5 public MyStack() { 6 queue = new LinkedList<>(); 7 8 } 9 10 /** Push element x onto stack. */ 11 public void push(int x) { 12 queue.offer(x); 13 int size = queue.size(); 14 for(int i = 0; i < size-1; i++){ 15 queue.offer(queue.remove()); 16 } 17 18 } 19 20 /** Removes the element on top of the stack and returns that element. */ 21 public int pop() { 22 return queue.remove(); 23 } 24 25 /** Get the top element. */ 26 public int top() { 27 return queue.peek(); 28 } 29 30 /** Returns whether the stack is empty. */ 31 public boolean empty() { 32 return queue.isEmpty(); 33 } 34 }