DEV Community

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

Posted on • Edited on

3 1

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:

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay