Skip to content

Instantly share code, notes, and snippets.

@imduffy15
Created January 10, 2013 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imduffy15/4504613 to your computer and use it in GitHub Desktop.
Save imduffy15/4504613 to your computer and use it in GitHub Desktop.
class LinkedSet<T> {
private class Node<T> {
private T item;
private Node<T> next;
Node(T item0, Node<T> next0) {
item = item0;
next = next0;
}
}
private Node<T> head = null;
public int size() {
Node<T> p = head;
int numItems = 0;
while(p!=null) {
numItems++;
p = p.next;
}
return numItems;
}
public boolean add(T t) {
if(contains(t)) return false;
head = new Node<T>(t,head);
return true;
}
public boolean contains(T t) {
Node<T> p = head;
while(p!=null && !equals(p.item,t)) {
p = p.next;
}
return p!=null;
}
public boolean remove(T t) {
Node<T> p =head;
Node<T> pPred = null;
while(p!=null && !equals(t,p.item)) {
pPred = p;
p=p.next;
}
if(p==null) return false;
if(p==head) head = head.next;
else pPred.next = p.next;
return true;
}
private boolean equals(T t1, T t2) {
if(t1!=null) return t1.equals(t2);
else return t2==null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment