Implement the following operations of a stack using queues.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty.
使用ArrayList ,记得添加泛型
class MyStack {
List<Integer> list=new ArrayList<Integer>();
int size=0;
// Push element x onto stack.
public void push(int x) {
list.add(size,x);
size++;
}
// Removes the element on top of the stack.
public void pop() {
list.remove(size-1);
size--;
}
// Get the top element.
public int top() {
return list.get(size-1);
}
// Return whether the stack is empty.
public boolean empty() {
return size==0;
}
}