225. Implement Stack using Queues
开始写了两个queue的,实在太丑了,不好意思贴上了,改成了一个queue
1 class MyStack { 2 Queue<Integer> queue = new LinkedList<Integer>(); 3 4 // Push element x onto stack. 5 public void push(int x) { 6 queue.add(x); 7 } 8 9 // Removes the element on top of the stack. 10 public void pop() { 11 int size = queue.size(); 12 for(int i = 0; i < size - 1; i++) { 13 queue.add(queue.poll()); 14 } 15 queue.poll(); 16 } 17 18 // Get the top element. 19 public int top() { 20 int size = queue.size(); 21 for(int i = 0; i < size - 1; i++) { 22 queue.add(queue.poll()); 23 } 24 int res = queue.poll(); 25 queue.add(res); 26 return res; 27 } 28 29 // Return whether the stack is empty. 30 public boolean empty() { 31 return queue.isEmpty(); 32 } 33 }

浙公网安备 33010602011771号