Docsity

Chain Data Structure Implementation in Java: Class, Constructors, Methods, and Performance, Slides of Computer Science

Partial preview of the text

Download Chain Data Structure Implementation in Java: Class, Constructors, Methods, and Performance and more Slides Computer Science in PDF only on Docsity!

The Class Chain

The Class Chain

next (datatype ChainNode) element (datatype Object)

Use ChainNode

a b c d e null firstNode

size = number of elements

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 isEmpty

/** @return true iff list is empty */

public boolean isEmpty()

{return size == 0;}

The Method checkIndex /** @throws IndexOutOfBoundsException when

  • index is not between 0 and size - 1 */ void checkIndex(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException ("index = " + index + " size = " + size); }

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

The Method indexOf

// make sure we found matching element if (currentNode == null) return -1; else return index; }

Removing An Element

remove(0) firstNode = firstNode.next; a b c d e null firstNode

remove(2)

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);

Two-Step add(3,โ€™fโ€™)

beforeNode = firstNode.next.next;

beforeNode.next = new ChainNode(โ€˜fโ€™, beforeNode.next);

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