11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

98 Chap. 4 Lists, Stacks, <strong>and</strong> Queues/** Array-based list implement<strong>at</strong>ion */class AList implements List {priv<strong>at</strong>e st<strong>at</strong>ic final int defaultSize = 10; // Default sizepriv<strong>at</strong>e int maxSize; // Maximum size of listpriv<strong>at</strong>e int listSize; // Current # of list itemspriv<strong>at</strong>e int curr;// Position of current elementpriv<strong>at</strong>e E[] listArray; // Array holding list elements/** Constructors *//** Cre<strong>at</strong>e a list with the default capacity. */AList() { this(defaultSize); }/** Cre<strong>at</strong>e a new list object.@param size Max # of elements list can contain. */@SuppressWarnings("unchecked") // Generic array alloc<strong>at</strong>ionAList(int size) {maxSize = size;listSize = curr = 0;listArray = (E[])new Object[size]; // Cre<strong>at</strong>e listArray}public void clear()// Reinitialize the list{ listSize = curr = 0; } // Simply reinitialize values/** Insert "it" <strong>at</strong> current position */public void insert(E it) {assert listSize < maxSize : "List capacity exceeded";for (int i=listSize; i>curr; i--) // Shift elements uplistArray[i] = listArray[i-1]; // to make roomlistArray[curr] = it;listSize++;// Increment list size}/** Append "it" to list */public void append(E it) {assert listSize < maxSize : "List capacity exceeded";listArray[listSize++] = it;}/** Remove <strong>and</strong> return the current element */public E remove() {if ((curr=listSize)) // No current elementreturn null;E it = listArray[curr]; // Copy the elementfor(int i=curr; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!