Skip to content

Instantly share code, notes, and snippets.

@cgmb
Last active August 29, 2015 14:15
Show Gist options
  • Save cgmb/55e2f4081bd552ef9e4a to your computer and use it in GitHub Desktop.
Save cgmb/55e2f4081bd552ef9e4a to your computer and use it in GitHub Desktop.
A singly-linked list in Java
import java.util.NoSuchElementException;
public class ForwardList<T> {
public ForwardList() {
head = tail = null;
}
public void insertAtHead(T data) {
Node<T> n = new Node<T>(data, head);
head = n;
if (tail == null) {
tail = n;
}
}
public boolean isEmpty() {
return head == null;
}
public Node<T> findFirst(T data) {
Node<T> currentNode = head;
while (currentNode != null) {
if (currentNode.data == data) {
return currentNode;
}
currentNode = currentNode.next;
}
return null;
}
public void removeAtHead() {
if (isEmpty()) {
throw new NoSuchElementException("List empty! Cannot remove from head!");
}
head = head.next;
if (head == null) {
tail = null;
}
}
public void removeAtTail() {
if (isEmpty()) {
throw new NoSuchElementException("List empty! Cannot remove from tail!");
}
if (head == tail) {
head = tail = null;
return;
}
Node<T> currentNode = head;
while (currentNode.next != tail) {
currentNode = currentNode.next;
}
currentNode.next = null;
tail = currentNode;
}
Node<T> head;
Node<T> tail;
}
public class Node<T> {
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
T data;
Node<T> next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment