Preview:
import java.util.LinkedList;

public class GenericStack<T> {
    private LinkedList<T> stackList;

    public GenericStack() {
        this.stackList = new LinkedList<>();
    }

    public void push(T item) {
        stackList.addFirst(item);
    }

    public T pop() {
        if (!stackList.isEmpty()) {
            return stackList.removeFirst();
        } else {
            System.out.println("Stack Underflow");
            return null;
        }
    }

    public boolean isEmpty() {
        return stackList.isEmpty();
    }

    public T peek() {
        if (!stackList.isEmpty()) {
            return stackList.getFirst();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        GenericStack<Integer> intStack = new GenericStack<>();
        intStack.push(1);
        intStack.push(2);
        intStack.push(3);
        intStack.push(4);
        intStack.push(5);

        System.out.println("Top element: " + intStack.peek()); // 5

        while (!intStack.isEmpty()) {
            System.out.println("Popped element: " + intStack.pop());
        }

        System.out.println("Stack is empty: " + intStack.isEmpty()); // true

        GenericStack<String> stringStack = new GenericStack<>();
        stringStack.push("one");
        stringStack.push("two");
        stringStack.push("three");

        System.out.println("Top element: " + stringStack.peek()); // three

        while (!stringStack.isEmpty()) {
            System.out.println("Popped element: " + stringStack.pop());
        }

        System.out.println("Stack is empty: " + stringStack.isEmpty()); // true
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter