Today's Class
During today's lecture, we discussed and implemented the following code for the linked list and node. We'll continued next class.
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; } }