/5a)user-defined generic stack

PHOTO EMBED

Sun May 26 2024 20:27:14 GMT+0000 (Coordinated Universal Time)

Saved by @prabhas

import java.util.Scanner;

class Node<T> {
    T data;
    Node<T> next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

class GenericStackArray<T> {
    private T[] stackArray;
    private int top;
    private int maxSize;

    @SuppressWarnings("unchecked")
    public GenericStackArray(int size) {
        this.maxSize = size;
        this.stackArray = (T[]) new Object[maxSize];
        this.top = -1;
    }

    public void push(T item) {
        if (top < maxSize - 1) {
            stackArray[++top] = item;
        } else {
            System.out.println("Stack Overflow");
        }
    }

    public T pop() {
        if (top >= 0) {
            return stackArray[top--];
        } else {
            System.out.println("Stack Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return top == -1;
    }
}

class GenericStackLinkedList<T> {
    private Node<T> top;

    public GenericStackLinkedList() {
        this.top = null;
    }

    public void push(T item) {
        Node<T> newNode = new Node<>(item);
        newNode.next = top;
        top = newNode;
    }

    public T pop() {
        if (top == null) {
            System.out.println("Stack Underflow");
            return null;
        }
        T data = top.data;
        top = top.next;
        return data;
   }

    public boolean isEmpty() {
        return top == null;
    }
}

public class GenericStackExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        GenericStackArray<Integer> intStackArray = new GenericStackArray<>(5);
        GenericStackLinkedList<Integer> intStackLinkedList = new GenericStackLinkedList<>();

        System.out.println("Enter integers to push into the array stack (enter -1 to stop):");
        int num;
        while (true) {
            num = scanner.nextInt();
            if (num == -1) break;
            intStackArray.push(num);
        }

        System.out.println("Enter integers to push into the linked list stack (enter -1 to stop):");
        while (true) {
 num = scanner.nextInt();
            if (num == -1) break;
            intStackLinkedList.push(num);
        }

        System.out.println("Popping from array stack:");
        while (!intStackArray.isEmpty()) {
            System.out.println(intStackArray.pop());
        }

        System.out.println("Popping from linked list stack:");
        while (!intStackLinkedList.isEmpty()) {
            System.out.println(intStackLinkedList.pop());
        }
    }
}
content_copyCOPY