Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created December 21, 2013 21:27
Show Gist options
  • Save ElectricCoffee/8075344 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/8075344 to your computer and use it in GitHub Desktop.
A Cons List in Java as an alternative to the ArrayList already found
public class ConsList<T extends Comparable<T>> {
private T _head;
private ConsList<T> _tail;
public ConsList(T head, ConsList<T> tail) {
_head = head;
_tail = tail;
}
public static <T extends Comparable<T>> ConsList<T> CreateList(T... items) {
int max = items.length -1;
ConsList<T> resultList = null;
for(int i = max; i > -1; i--) {
if(i == max)
resultList = new ConsList<T>(items[i], null);
else
resultList = resultList.add(items[i]);
}
return resultList;
}
public T getHead() {
return _head;
}
public ConsList<T> getTail() {
return _tail;
}
public boolean isTailEmpty() {
if(_tail == null)
return true;
else return _tail.isEmpty();
}
public boolean isEmpty() {
if(_head == null && (_tail == null || _tail.isEmpty())) return true;
else return false;
}
public ConsList<T> add(T item) {
return new ConsList<T>(item, this);
}
@Override
public String toString() {
if(_tail != null)
return _head.toString() + ", " + _tail.toString();
else
return _head.toString() + "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment