Implement the following operations of a stack using queues.spa
Notes:code
push to back
, peek/pop from front
, size
, and is empty
operations are valid.
題目大意:用隊列,實現棧。blog
class MyStack { List<Integer> stack = new ArrayList<>(); // Push element x onto stack. public void push(int x) { stack.add(x); } // Removes the element on top of the stack. public void pop() { if(!empty()){ stack.remove(stack.size()-1); } } // Get the top element. public int top() { if(!empty()){ return stack.get(stack.size()-1); } return -1; } // Return whether the stack is empty. public boolean empty() { return stack.size()==0; } }