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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
class MyStack { Queue<Integer> q = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { q.add(x); for(int i = 0; i < q.size()-1 ;i++){ q.add(q.remove()); } } // Removes the element on top of the stack. public void pop() { q.remove(); } // Get the top element. public int top() { return q.peek(); } // Return whether the stack is empty. public boolean empty() { return q.isEmpty(); } }