Implement the following operations of a stack using queues.
Notes:
push to back
, peek/pop from front
, size
, and is empty
operations are valid.
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
class MyStack { Queue<Integer> queue = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { queue.add(x); int n = queue.size(); while(n>1) { queue.add(queue.poll()); n--; } } // Removes the element on top of the stack. public void pop() { queue.poll(); } // Get the top element. public int top() { return queue.peek(); } // Return whether the stack is empty. public boolean empty() { return queue.isEmpty(); } }
原文:http://www.cnblogs.com/hygeia/p/5126120.html