Linked Lists

  • similar to array list
  • add an element adds a container
  • each container linked to the other
import java.util.LinkedList;

public class Cars {
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  }
}
Cars.main(null);
[Volvo, BMW, Ford, Mazda]

Stack

  • push: inserts object to the top of the stack
  • pop: removes object from top of stack
public class StackLinkedList<T> {
    private Node<T> top;
    private int size;

    public StackLinkedList() {
        this.top = null;
        this.size = 0;
    }

    public boolean isEmpty() {
        return top == null;
    }

    public int size() {
        return size;
    }

    public void push(T data) {
        Node<T> newNode = new Node<>(data);
        if (isEmpty()) {
            top = newNode;
        } else {
            newNode.next = top;
            top = newNode;
        }
        size++;
    }

    public T pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("Stack is empty");
        }
        T data = top.data;
        top = top.next;
        size--;
        return data;
    }

    public T peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("Stack is empty");
        }
        return top.data;
    }

    private static class Node<T> {
        private T data;
        private Node<T> next;

        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }
}

Queue

  • first in first out
  • elements inserted at any time
  • element that has been in the longest is the first removed