In: Computer Science
Code in Java
Create a stack class to store integers and implement following methods:
1) void push(int num): This method will push an integer to the top of the stack.
2) int pop(): This method will return the value stored in the top of the stack. If the stack is empty this method will return -1.
3) void display(): This method will display all numbers in the stack from top to bottom (First item displayed will be the top value).
4) Boolean isEmpty(): This method will check the stack and if it is empty, this will return true, otherwise false.
public class IntegerStack {
    static class Node {
        int data;
        Node next;
    }
    private Node head;
    public void push(int num) {
        Node n = new Node();
        n.data = num;
        n.next = null;
        if (head == null) {
            head = n;
        } else {
            n.next = head;
            head = n;
        }
    }
    public int pop() {
        if (head == null) {
            return -1;
        } else {
            int result = head.data;
            head = head.next;
            return result;
        }
    }
    public void display() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }
    public Boolean isEmpty() {
        return head == null;
    }
    public static void main(String[] args) {
        IntegerStack stack = new IntegerStack();
        stack.push(3);
        stack.push(4);
        stack.push(9);
        stack.push(1);
        stack.push(5);
        stack.display();
        while (!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");
        }
        System.out.println();
    }
}
