Here is the code we wrote today. First the OurList interface:
public interface OurList< T> {
public void add(T s); //adds s to end
public int size(); //returns size of list
public boolean contains(T s); //returns whether s is in the list
public void clear(); //empties list
}
And then the OurLinkedList class:
public class OurLinkedList< T> implements OurList< T> {
private Node head; //points to head of list
private class Node {
T value;
Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
}
public void addFront(T newItem) {
head = new Node(newItem, head);
}
public boolean contains(T s) {
Node curr = head;
while(curr != null) {
if(curr.value.equals(s))
return true;
curr = curr.next;
}
return false;
}
public int size() {
Node curr = head;
int count = 0;
while(curr != null) {
count++;
curr = curr.next;
}
return count;
}
public void clear() {
head = null;
}
public void add(T toAdd) { //add to end of the list
Node curr = head;
Node newNode = new Node(toAdd, null);
if(curr == null) { //special case: adding to empty list
head = newNode;
return;
}
while(curr.next != null)
curr = curr.next;
curr.next= newNode;
}
}