DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published at jsedano.dev on

2 2

Stack

My notes on the stack abstract data type with an implementation using an array in Java.

You can find the complete code for this and other data structures here: data structures and algorithms

A stack is an abstract data type that mimics a real world stack where you can place elements on the top or you can take the top element. The behavior of the stack is described as last in first out (LIFO).

Common Operations for a stack includes:

Operation Complexity
push(element) O(1)
pop() O(1)

Push will place a new element on the top of the stack.

node

public boolean push(T valueToPush) {
    if(size == innerArray.length) {
        return false;
    }
    innerArray[size] = valueToPush;
    size++;
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Pop takes out the top element from the stack and returns it.

node

public T pop() {
    if(size == 0) {
        throw new NullPointerException("empty stack");
    }
    T valueToPop = innerArray[size - 1];
    innerArray[size - 1] = null;
    size--;
    return valueToPop;
}
Enter fullscreen mode Exit fullscreen mode

In this implementation the capacity of the stack is the capacity of the inner array. We keep track of the size of the stack by increasing or decreasing the size with every pop and push, by doing this we always know that top is at innerArray[size-1] and when we do a push we put new element at innerArray[size].

Implementing a stack using a linked list would be even easier because we can keep prepending a new node to the linked list with every push and for the pop we only need to get the first element, remove it from the list and then return it.

Download the complete code for this and other data structures here: data structures and algorithms.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay