Created
January 10, 2013 18:37
-
-
Save imduffy15/4504613 to your computer and use it in GitHub Desktop.
This file contains 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 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