DEV Community

Cover image for Data Structure In Java: Dynamic Stack
luthfisauqi17
luthfisauqi17

Posted on • Edited on

Data Structure In Java: Dynamic Stack

import java.util.EmptyStackException;

public class StackDynamic<T> {
    private class StackNode {
        private T data;
        private StackNode next;

        private StackNode(T data) {
            this.data = data;
            this.next = null;
        }
    }

    private StackNode top;

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

    public StackDynamic(T data) {
        this.top = new StackNode(data);
    }

    public T pop() {
        if (this.top == null) throw new EmptyStackException();
        T data = this.top.data;
        this.top = this.top.next;
        return data;
    }

    public void push(T data) {
        StackNode temp = new StackNode(data);
        temp.next = this.top;
        this.top = temp;
    }

    public T peek() {
        if (this.top == null) throw new EmptyStackException();
        return this.top.data;
    }

    public boolean isEmpty() {
        return this.top == null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Sources and Images:

Top comments (0)