Created
September 25, 2017 19:53
-
-
Save aaronjwood/bd1f1654575b5cd0970f207da78cc679 to your computer and use it in GitHub Desktop.
Queue using a linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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