COP 3530: Data Structures, Algorithms, & Applications
description
Transcript of COP 3530: Data Structures, Algorithms, & Applications
COP 3530: Data COP 3530: Data Structures, Algorithms, & Structures, Algorithms, &
ApplicationsApplications
Instructor: Kristian Linn Instructor: Kristian Linn DamkjerDamkjer
Linear List ImplementationLinear List Implementation
ArrayLinearListArrayLinearList
About About ArrayLinearListArrayLinearListGeneral purpose implementation General purpose implementation
of linear lists.of linear lists.Describes one way of creating the Describes one way of creating the
Data Structure: Data Structure: Linear ListLinear ListImplements the Implements the LinearListLinearList
interfaceinterfaceMay contain methods in addition to May contain methods in addition to
those specified in those specified in LinearListLinearList
Creating New ListsCreating New ListsAll lists are initially emptyAll lists are initially empty
This is simply by design, not a This is simply by design, not a limitationlimitation
What must we consider?What must we consider?Use of data structure in programUse of data structure in programInitial size of arrayInitial size of array
Examples:Examples:ArrayLinearList a = ArrayLinearList a = newnew ArrayLinearList(100), ArrayLinearList(100), b = b = newnew ArrayLinearList(), ArrayLinearList(), c;c;LinearList d = LinearList d = newnew ArrayLinearList(100), ArrayLinearList(100), e = e = newnew ArrayLinearList(), ArrayLinearList(), f;f;
Oppsie! Oppsie! ArrayLinearList a = ArrayLinearList a = newnew LinearList(100), LinearList(100),
b = b = newnew LinearList(), LinearList(),
c;c;
LinearList d = LinearList d = newnew LinearList(100), LinearList(100),
e = e = newnew LinearList(), LinearList(),
f;f;
WRONG
WRONG
Using Linear ListsUsing Linear ListsShould not depend on the Should not depend on the
implementationimplementationExample:Example:
System.out.println(a.size());System.out.println(a.size());
a.add(0, a.add(0, newnew Integer(2)); Integer(2));
b.add(0, b.add(0, newnew Integer(4)); Integer(4));
System.out.println(a);System.out.println(a);
b.remove(0);b.remove(0);
ifif (a.isEmpty()) (a.isEmpty())
a.add(0, new Integer(5));a.add(0, new Integer(5));
Why keep it generic?Why keep it generic? Consider an array of Linear ListsConsider an array of Linear Lists By declaring the array as type By declaring the array as type LinearListLinearList, we , we
may store any instances of any may store any instances of any implementation we wish.implementation we wish.
Example:Example:LinearList[] x = LinearList[] x = newnew LinearList[4]; LinearList[4];x[0] = x[0] = newnew ArrayLinearList(20); ArrayLinearList(20);x[1] = x[1] = newnew Chain(); Chain();x[2] = x[2] = newnew Chain(); Chain();x[3] = x[3] = newnew ArrayLinearList(); ArrayLinearList();
forfor ( (intint i = 0; i < 4; i++) i = 0; i < 4; i++) x[i].add(0, x[i].add(0, newnew Integer(i)); Integer(i));
Linear List ImplementationLinear List Implementation
Class StructureClass Structure
Skeletal StructureSkeletal Structure/** array implementation of LinearList *//** array implementation of LinearList */
packagepackage dataStructures; dataStructures;
importimport java.util.*; java.util.*; // Java utilities package for Iterator// Java utilities package for Iterator
importimport utilities.*; utilities.*; // Our utilities package for resizing// Our utilities package for resizing
public classpublic class ArrayLinearList ArrayLinearList implementsimplements LinearList { LinearList {
// data members// data members
protectedprotected Object[] element; Object[] element; // array of elements// array of elements
protected intprotected int size; size; // number of elements in array// number of elements in array
// constructors// constructors
// methods// methods
}}
Linear List ImplementationLinear List Implementation
ConstructorsConstructors
ConstructorConstructor/**/**
* Create a list with initial capacity initialCapacity* Create a list with initial capacity initialCapacity
* @throws IllegalArgument Exception when initialCapacity < 1* @throws IllegalArgument Exception when initialCapacity < 1
*/*/
public public ArrayLinearList(int initialCapacity) {ArrayLinearList(int initialCapacity) {
if if (initialCapacity < 1)(initialCapacity < 1)
throw newthrow new IllegalArgumentException( IllegalArgumentException(
""initialCapacity must be >= 1initialCapacity must be >= 1""););
// size has the default initial value of 0// size has the default initial value of 0
element = element = newnew Object[initialCapacity]; Object[initialCapacity];
}}
No-Argument ConstructorNo-Argument Constructor/**/**
* Create a list with initial capacity 10* Create a list with initial capacity 10
*/*/
public public ArrayLinearList() {ArrayLinearList() {
// use the default capacity of 10// use the default capacity of 10
thisthis(10);(10);
}}
Linear List ImplementationLinear List Implementation
MethodsMethods
isEmpty()isEmpty()/** @return true if and only if the list is empty *//** @return true if and only if the list is empty */
public boolean public boolean isEmpty() {isEmpty() {
returnreturn size == 0; size == 0;
}}
size()size()/** @return current number of elements in the list *//** @return current number of elements in the list */
public int public int size() {size() {
returnreturn size; size;
}}
checkIndex()checkIndex()/** @throws IndexOutOfBoundsException *//** @throws IndexOutOfBoundsException */
void void checkIndex(checkIndex(intint index) { index) {
ifif (index < 0 || index >= size) (index < 0 || index >= size)
throw newthrow new IndexOutOfBoundsException( IndexOutOfBoundsException(
""index = index = "" + index + + index + ""size = size = "" + size); + size);
}}
get()get()/**/**
* @return element with specified index* @return element with specified index
* @throws IndexOutOfBoundsException when index is not* @throws IndexOutOfBoundsException when index is not
* between 0 and size - 1* between 0 and size - 1
*/*/
public public Object get(Object get(intint index) { index) {
checkIndex(index);checkIndex(index);
returnreturn element[index]; element[index];
}}
indexOf()indexOf()/**/**
* @return index of first occurrence of theElement,* @return index of first occurrence of theElement,
* return -1 if theElement is not in the list* return -1 if theElement is not in the list
*/*/
public int public int indexOf(Object theElement) {indexOf(Object theElement) {
// search element[] for theElement// search element[] for theElement
forfor ( (intint i = 0; i < size; i++) i = 0; i < size; i++)
ifif (element[i].equals(theElement)) (element[i].equals(theElement))
returnreturn i; i;
// return -1 if theElement was not found// return -1 if theElement was not found
returnreturn -1; -1;
}}
remove()remove()/**/** * Remove the element with specified index and update indices* Remove the element with specified index and update indices * @throws IndexOutOfBoundsException when index is not* @throws IndexOutOfBoundsException when index is not * between 0 and size - 1* between 0 and size - 1 * @return removed element* @return removed element */*/publicpublic Object remove(int index) { Object remove(int index) { checkIndex(index);checkIndex(index);
// valid index, shift elements with higher index// valid index, shift elements with higher index Object removedElement = element[index];Object removedElement = element[index]; forfor ( (intint i = index + 1; i < size; i++) i = index + 1; i < size; i++) element[i – 1] = element[i];element[i – 1] = element[i];
element[--size] = element[--size] = nullnull; ; // enable garbage collection// enable garbage collection returnreturn removedElement; removedElement;}}
add()add()/**/** * Insert an element with specified index. All elements with* Insert an element with specified index. All elements with * equal or higher index have their index increased by 1.* equal or higher index have their index increased by 1. * @throws IndexOutOfBoundsException when index is not* @throws IndexOutOfBoundsException when index is not * between 0 and size* between 0 and size */*/public void public void add(add(intint index, Object theElement) { index, Object theElement) {
ifif (index < 0 || index > size) (index < 0 || index > size)
// invalid list position// invalid list position throw newthrow new IndexOutOfBoundsException( IndexOutOfBoundsException( ""index = index = "" + index + + index + ""size = size = "" + size); + size);
add()add()
// valid index, make sure we have space// valid index, make sure we have space ifif (size == element.length) (size == element.length)
// if no space, double capacity// if no space, double capacity element = ChangeArrayLength.changeLength1D(element,element = ChangeArrayLength.changeLength1D(element, 2 *size);2 *size);
// shift elements right one position// shift elements right one position forfor ( (intint i = size – 1; i >= index; i--) i = size – 1; i >= index; i--) element[i + 1] = element[i];element[i + 1] = element[i];
// insert the element and increase size// insert the element and increase size element[index] = theElement;element[index] = theElement; size++;size++;}}
Faster ShiftFaster Shift
System.arraycopy(System.arraycopy(
// original array// original array element,element,
// starting index in original// starting index in original index,index,
// target array// target array element,element,
// starting index in target// starting index in target index + 1,index + 1,
// number of elements to copy// number of elements to copy size – indexsize – index ););
toString()toString()/** convert to a String *//** convert to a String */publicpublic String toString() { String toString() { StringBuffer s = StringBuffer s = newnew StringBuffer( StringBuffer("[""["););
// put elements into the buffer// put elements into the buffer forfor ( (intint i = 0; i < size; i++) i = 0; i < size; i++) ifif (element[i] == (element[i] == nullnull)) s.append(s.append("null, ""null, ");); elseelse s.append(element[i].toString() + s.append(element[i].toString() + ", "", "););
ifif (size > 0) (size > 0) s.delete(s.length() – 2, s.length()); s.delete(s.length() – 2, s.length()); //remove last ", "//remove last ", "
s.append(s.append("]""]"););
// create equivalent String// create equivalent String return newreturn new String(s); String(s);}}
IteratorsIterators
DefinitionDefinition
What is an iterator?What is an iterator?An iterator facilitates the iterative An iterator facilitates the iterative
examination of data structure examination of data structure elementselementsWe will often need to examine all We will often need to examine all
elements in a data structureelements in a data structureRepeated Repeated getget operations usually have operations usually have
a lot of unnecessary overheada lot of unnecessary overheadNot all structures have a Not all structures have a getget behavior behavior
Java provides Java provides IteratorIterator as an as an interfaceinterface
IteratorIterator
MethodsMethods
Creating IteratorsCreating Iterators
Contrary to what you’re used to, Contrary to what you’re used to, iterators are generally not iterators are generally not instantiated directly.instantiated directly.
Iterator ix = new IteratorImplementation();Iterator ix = new IteratorImplementation();
Instead you should use the Instead you should use the iteratoriterator method which must be defined for method which must be defined for IteratorIterator implementations implementations
Iterator ix = myObject.iterator();Iterator ix = myObject.iterator();
DON’T DO THIS
DON’T DO THIS
What can iterators do?What can iterators do? Iterators are very simple, they only have Iterators are very simple, they only have
three behaviors in addition to three behaviors in addition to iteratoriteratorThey can correctly identify whether or not They can correctly identify whether or not
there is an element immediately after the there is an element immediately after the current elementcurrent element
They can tell us what the next element is, if They can tell us what the next element is, if there is onethere is oneHas the side-effect of making the next element the Has the side-effect of making the next element the
currently examined elementcurrently examined element
They may be able to remove the current They may be able to remove the current element, though this is not always guaranteedelement, though this is not always guaranteed
Behavior DetailsBehavior DetailsThe The IteratorIterator method method hasNexthasNext
determines the existence of a next determines the existence of a next element.element.Returns Returns truetrue if and only if there is a next if and only if there is a next
elementelement
The The IteratorIterator method method nextnext identifies identifies the next element if it exists.the next element if it exists.Throws Throws NoSuchElementExceptionNoSuchElementException if there is if there is
no next elementno next elementReturns and advances to the next element Returns and advances to the next element
otherwiseotherwise
Optional BehaviorOptional BehaviorThe The IteratorIterator method method removeremove removes removes
the last element that was returned by the last element that was returned by nextnext
removeremove is not necessarily supported is not necessarily supportedThrows Throws UnsupportedMethodExceptionUnsupportedMethodException if the if the
method is not implementedmethod is not implementedThrows Throws IllegalStateExceptionIllegalStateException if if nextnext has has
not been called or did not return an elementnot been called or did not return an elementRemoves the last element returned by Removes the last element returned by nextnext
otherwiseotherwise
Using IteratorsUsing Iterators
What you’re used to doing:What you’re used to doing:
forfor ( (intint i = 0; i < x.size(); i++) i = 0; i < x.size(); i++)
doSomthingWith(x.get(i));doSomthingWith(x.get(i));
Now with an iterator:Now with an iterator:
Iterator ix = x.iterator();Iterator ix = x.iterator();
whilewhile(ix.hasNext())(ix.hasNext())
doSomethingWith(ix.next());doSomethingWith(ix.next());
Why Use Iterators?Why Use Iterators?
It is often possible to implement It is often possible to implement nextnext so that its complexity is less so that its complexity is less than that of than that of getget
Many data structures do not have Many data structures do not have a a getget behavior behavior
Iterators provide a uniform way to Iterators provide a uniform way to step through the elements of a step through the elements of a data structuredata structure
What Would Java Do?What Would Java Do?
java.util.ArrayListjava.util.ArrayList
It’s the Cadillac version of our It’s the Cadillac version of our ArrayLinearListWithIteratorArrayLinearListWithIterator
Next Time in COP 3530…Next Time in COP 3530…Link-Based Representation of Link-Based Representation of
Linear ListLinear ListLink-Based Implementation of Link-Based Implementation of
Linear List (a.k.a. Chain)Linear List (a.k.a. Chain)Read Chapter 6Read Chapter 6
Yes, all of itYes, all of it