Here is the code from today:
public class OurLinkedList {
private Node first; //first node in list
public OurLinkedList() {
first = null;
}
public int size() {
Node temp = first;
int retVal = 0;
while(temp != null) {
retVal++;
temp = temp.next;
}
return retVal;
}
public void clear() {
first = null;
}
public String get(int index) {
if(index < 0)
throw new IndexOutOfBoundsException();
Node temp = first;
for(int i=0; i< index; i++) {
if(temp == null)
throw new IndexOutOfBoundsException();
temp = temp.next;
}
if(temp == null)
throw new IndexOutOfBoundsException();
return temp.value;
}
public void addFirst(String value) { //add to front of list
Node addedNode = new Node();
addedNode.value = value;
addedNode.next = first;
first = addedNode;
}
public void add(String value) { //add value to end of list
Node addedNode = new Node();
addedNode.value = value;
addedNode.next = null;
if(first == null)
first = addedNode;
else {
Node temp = first;
while(temp.next != null)
temp = temp.next;
temp.next = addedNode;
}
}
public void set(int index, String value) {
if(index < 0)
throw new IndexOutOfBoundsException();
Node temp = first;
int currIndex = 0;
while((temp != null) && (currIndex < index)) {
temp = temp.next;
currIndex++;
}
if(temp == null)
throw new IndexOutOfBoundsException();
temp.value = value;
}
public void add(int index, String value) {
if(index < 0)
throw new IndexOutOfBoundsException();
Node addedNode = new Node();
addedNode.value = value;
if(index == 0) {
addFirst(value);
return;
}
Node temp = first;
int currIndex = 0;
while((temp != null) && (currIndex < index-1)) {
temp = temp.next;
currIndex++;
}
if(temp == null)
throw new IndexOutOfBoundsException();
addedNode.next = temp.next;
temp.next = addedNode;
}
}
class Node {
public String value;
public Node next;
}