Implement Stack using Queues
用queue写一个stack. 这里有很多的不同实现方法, 最简单的就是当push的时候, 改成stack.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class MyStack { // Push element x onto stack. Queue<Integer> q = new LinkedList<Integer>(); public void push(int x) { q.offer(x); for(int i = 0 ; i < q.size()-1; i++){ q.offer(q.peek()); q.poll(); } } // Removes the element on top of the stack. public void pop() { q.poll(); } // Get the top element. public int top() { return q.peek(); } // Return whether the stack is empty. public boolean empty() { return q.isEmpty(); } } |