// "static void main" must be defined in a public class.classMyStack {privateList<Integer> data; // store elementspublicMyStack() { data =newArrayList<>(); } /** Insert an element into the stack. */publicvoidpush(int x) {data.add(x); } /** Checks whether the queue is empty or not. */publicbooleanisEmpty() {returndata.isEmpty(); } /** Get the top item from the queue. */publicinttop() {returndata.get(data.size() -1); } /** Delete an element from the queue. Return true if the operation is successful. */publicbooleanpop() {if (isEmpty()) {returnfalse; }data.remove(data.size() -1);returntrue; }};publicclassMain {publicstaticvoidmain(String[] args) {MyStack s =newMyStack();s.push(1);s.push(2);s.push(3);for (int i =0; i <4; ++i) {if (!s.isEmpty()) {System.out.println(s.top()); }System.out.println(s.pop()); } }}
Stack Usage
Java has a class called java.util.Stack:
pop(), push()
// "static void main" must be defined in a public class.publicclassMain {publicstaticvoidmain(String[] args) {// 1. Initialize a stack.Stack<Integer> s =newStack<>();// 2. Push new element.s.push(5);s.push(13);s.push(8);s.push(6);// 3. Check if stack is empty.if (s.empty() ==true) {System.out.println("Stack is empty!");return; }// 4. Pop an element.s.pop();// 5. Get the top element.System.out.println("The top element is: "+s.peek());// 6. Get the size of the stack.System.out.println("The size is: "+s.size()); }}
A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.