Basic Java linked list stack implementation

Software


Appropriate photo of plate stacks by Egan Snow on The Wikipedias.

Linked lists are useful for replicating and extending the functionality of object arrays, but they can also be used to replicate other linear strings of data such as a stack. From my high school days as an Apprentice Perl Monk I got used to using push and pop with arrays and hashes; turns out they were functions for a form of stack.

As a crude Java implementation to demonstrate the concept, first I defined Stack and Node classes with constructors to accept a head and payload respectively. The Stack has a header Node. Each Node consists of a payload and the "next" Node.

public class Stack {
  Node head;
  public Stack(Object payload) {
    if (payload)
      head = new Node(payload);
  }
  private class Node {
    Object payload;
    Node next;
    public Node(Object payload) {
      this.payload = payload;
    }
  }
}

The basic push method for the stack pushes (really?!) objects onto the linked list. If there aren't any nodes, I assign the parameter to the head.

public void push(Object payload) {
  Node newNode = new Node(payload);
  if (head == null)
    head = newNode;
  else {
    newNode.next = head;
    head = newNode;
  }
}

The pop method is even simpler, it returns the payload in the Node head, then assign head to the next Node, mimicking how a stack [of plates] would work.

public Object pop() {
  Object toReturn = head.payload;
  head = head.next;
  return toReturn;
}

It's very late and I need to pop off to sleep, but tomorrow I'll be trying this out and applying it to some problems. If you can see a mistake or if you have a suggestion on how to make it better, I'd love to get your appreciated feedback :).

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.