Skip to content

Instantly share code, notes, and snippets.

@aaronjwood
Created September 25, 2017 19:53
Show Gist options
  • Save aaronjwood/bd1f1654575b5cd0970f207da78cc679 to your computer and use it in GitHub Desktop.
Save aaronjwood/bd1f1654575b5cd0970f207da78cc679 to your computer and use it in GitHub Desktop.
Queue using a linked list
class Queue<T> {
private static class Node<D> {
private D data;
private Node<D> previous;
private Node<D> next;
private Node(D data) {
this.data = data;
}
}
private int size;
private Node<T> head;
private Node<T> tail;
T getFirst() {
return head == null ? null : head.data;
}
T getLast() {
return tail == null ? null : tail.data;
}
void add(T data) {
Node<T> n = new Node<>(data);
size++;
if (head == null || tail == null) {
head = tail = n;
return;
}
n.next = tail;
tail.previous = n;
tail = n;
}
T remove() {
if (head == null) {
return null;
}
Node<T> n = head;
head = head.previous;
size--;
return n.data;
}
T peek() {
return head == null ? null : head.data;
}
int length() {
return size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment