






















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!























next (datatype ChainNode) element (datatype Object)
a b c d e null firstNode
Constructors /** create a list that is empty */ public Chain(int initialCapacity) { // the default initial values of firstNode and size // are null and 0, respectively } public Chain() {this(0);}
The Method checkIndex /** @throws IndexOutOfBoundsException when
The Method get public Object get(int index) { checkIndex(index); // move to desired node ChainNode currentNode = firstNode; for (int i = 0; i < index; i++) currentNode = currentNode.next; return currentNode.element; } a b c d e null firstNode Docsity.com
// make sure we found matching element if (currentNode == null) return -1; else return index; }
remove(0) firstNode = firstNode.next; a b c d e null firstNode
Find beforeNode and change its pointer. beforeNode.next = beforeNode.next.next; beforeNode a b c d e null firstNode
Remove An Element else { // use q to get to predecessor of desired node ChainNode q = firstNode; for (int i = 0; i < index - 1; i++) q = q.next; removedElement = q.next.element; q.next = q.next.next; // remove desired node } size--; return removedElement; }
Add An Element public void add(int index, Object theElement) { if (index < 0 || index > size) // invalid list position throw new IndexOutOfBoundsException ("index = " + index + " size = " + size); if (index == 0) // insert at front firstNode = new ChainNode(theElement, firstNode);
a b c d e null firstNode f newNode beforeNode c
Performance 40,000 operations of each type
Performance 40,000 operations of each type Operation FastArrayLinearList Chain get 5.6ms 157sec best-case adds 31.2ms 304ms average adds 5.8sec 115sec worst-case adds 11.8sec 157sec best-case removes 8.6ms 13.2ms average removes 5.8sec 149sec worst-case removes 11.7sec 157sec