Implement Stack
Implement a stack. You can use any data structure inside a stack except stack itself to implement it.
Example
push(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false
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 27 28 | class Stack { private ArrayList<Integer> stack = new ArrayList<Integer>(); // Push a new item into the stack public void push(int x) { // Write your code here stack.add(x); } // Pop the top of the stack public void pop() { // Write your code here stack.remove(stack.size() - 1); } // Return the top of the stack public int top() { // Write your code here return stack.get(stack.size() - 1); } // Check the stack is empty or not. public boolean isEmpty() { // Write your code here return stack.size() == 0; } } |