Today's Class
Today we wrapped up the basic linked list class. Below is our final version of the code.
The LinkedListNode Implementation
class LinkedList {
private Node head;
private Node tail;
private int count;
private class Node {
private Object item;
private Node next;
public Node (Object item, Node next) {
this.item = item;
this.next = next;
}
public Node (Object item) {
this.item = item;
this.next = null;
}
public Object getItem() {
return item;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public boolean equals(Object o) {
Node n = (Node) o;
if (!this.item.equals(n.item))
return false;
if (this.next != n.next)
return false;
return true;
}
public String toString() {
if (next != null)
return "" + getItem() + "--->" + next.getItem();
else
return "" + getItem() + "--->" + "END";
}
}
public LinkedList() {
head = tail = null;
count = 0;
}
public void addFirst(Object o) {
head = new Node (o, head);
if (count == 0)
tail = head;
count++;
}
public void addLast(Object o) {
Node end;
end = new Node (o, null);
tail.setNext(end);
tail = end;
count++;
}
public Object removeFirst() {
if (count == 0)
return null;
Object savedItem = head.getItem();
head = head.getNext();
count--;
if (count == 0)
tail = null;
return savedItem;
}
public Object removeLast() {
if (count == 0)
return null;
if (count == 1)
return removeFirst();
Object savedItem = tail.getItem();
Node index;
for (index=head; index.getNext() != tail; index = index.getNext())
;
index.setNext(tail.getNext());
return savedItem;
}
public Object getNth (int n) {
if ((n < 0) || (n >= count))
return null;
Node index=head;
for (int count=0; (count < n) ; index = index.getNext(), count++)
;
return index.getItem();
}
public void insertAtN (Object o, int n) {
if ( (n < 0) || (n > count))
return;
if (n == 0) {
addFirst (o);
return;
}
if (n == count) {
addLast(o);
return;
}
Node index;
int count;
for (index=head, count=0; (count < (n-1)); index = index.getNext())
;
index.setNext (new Node(o, index.getNext()));
this.count++;
}
}