Lists and Iterators CSC311: Data Structures 1 Chapter 6 Lists and Iterators Objectives Array Lists...

30
Lists and Iterators Lists and Iterators CSC311: Data Structures CSC311: Data Structures 1 Chapter 6 Chapter 6 Lists and Iterators Lists and Iterators Objectives Objectives Array Lists and Vectors: ADT and Array Lists and Vectors: ADT and Implementation Implementation Node Lists: ADT and Implementations Node Lists: ADT and Implementations Iterators: ADT and Implementation Iterators: ADT and Implementation List ADTs and Collections List ADTs and Collections Design Patterns Design Patterns Adaptor Pattern Adaptor Pattern Position Pattern Position Pattern Iterator Pattern Iterator Pattern
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    234
  • download

    2

Transcript of Lists and Iterators CSC311: Data Structures 1 Chapter 6 Lists and Iterators Objectives Array Lists...

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 11

Chapter 6Chapter 6Lists and IteratorsLists and Iterators

ObjectivesObjectivesArray Lists and Vectors: ADT and Array Lists and Vectors: ADT and ImplementationImplementationNode Lists: ADT and ImplementationsNode Lists: ADT and ImplementationsIterators: ADT and ImplementationIterators: ADT and ImplementationList ADTs and Collections List ADTs and Collections Design PatternsDesign Patterns– Adaptor PatternAdaptor Pattern– Position PatternPosition Pattern– Iterator PatternIterator Pattern

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 22

The Array List (Vector) ADT The Array List (Vector) ADT The The Array ListArray List ADT ADT extends the notion of extends the notion of array by storing a array by storing a sequence of arbitrary sequence of arbitrary objectsobjectsAn element can be An element can be accessed, inserted or accessed, inserted or removed by specifying removed by specifying its rank (number of its rank (number of elements preceding it)elements preceding it)An exception is thrown An exception is thrown if an incorrect rank is if an incorrect rank is specified (e.g., a specified (e.g., a negative rank)negative rank)

Main Array List operations:Main Array List operations:– object object getget(int r): returns the (int r): returns the

element at rank r without element at rank r without removing itremoving it

– object object setset(int r, Object o): (int r, Object o): replace the element at rank replace the element at rank with o and return the old with o and return the old elementelement

– addadd(int r, Object o): insert a (int r, Object o): insert a new element o to have rank rnew element o to have rank r

– object object remove remove (int r): (int r): removes and returns the removes and returns the element at rank relement at rank r

Additional operations Additional operations sizesize() and () and isEmptyisEmpty()()

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 33

Applications of Array ListsApplications of Array Lists

Direct applicationsDirect applications– Sorted collection of objects (elementary Sorted collection of objects (elementary

database)database)

Indirect applicationsIndirect applications– Auxiliary data structure for algorithmsAuxiliary data structure for algorithms– Component of other data structuresComponent of other data structures

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 44

Adaptor PatternAdaptor PatternAdaptor PatternAdaptor Pattern: : adapting an existing adapting an existing class to a new classclass to a new class

Contains an instance of Contains an instance of the existing class as a the existing class as a instance field, and instance field, and implement each implement each method of the new method of the new class by calling the class by calling the method of the instance method of the instance field objectfield object

Adapt Array List ADT to Adapt Array List ADT to Deque ADT Deque ADT

class Deque {class Deque {

private ArrayList al;private ArrayList al;

public Deque() {public Deque() {

al = new ArrayList();al = new ArrayList();

} }

public Object getFirst() {public Object getFirst() {

return al.get(0);return al.get(0);

}}

public void addFirst(Object e) {public void addFirst(Object e) {

al.add(0, e);al.add(0, e);

}}

public Object removeFirst() {public Object removeFirst() {

return al.remove(0);return al.remove(0);

}}

……

}}

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 55

Array-based ImplementationArray-based Implementation

Use an array Use an array VV of size of size NNA variable A variable nn keeps track of the size of the keeps track of the size of the array list (number of elements stored)array list (number of elements stored)Operation Operation getget((rr) is implemented in ) is implemented in OO(1)(1) time time by returning by returning VV[[rr]]

V0 1 2 nr

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 66

InsertionInsertionIn operation In operation addadd((rr,, o o), we ), we need to make room for the need to make room for the new element by shifting new element by shifting forward the forward the n n r r elements elements VV[[rr], …, ], …, VV[[n n 1]1]In the worst case (In the worst case (r r 00), this ), this takes takes OO((nn)) time time

V0 1 2 nr

V0 1 2 nr

V0 1 2 n

or

Algorithm add(i, e)for t = n 1 to i do

A[t+1] A[t]A[t] en n+1

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 77

DeletionDeletionIn operation In operation removeremove((rr), we ), we need to fill the hole left by need to fill the hole left by the removed element by the removed element by shifting backward the shifting backward the n n r r 11 elements elements VV[[r r 1], …, 1], …, VV[[n n 1]1]In the worst case (In the worst case (r r 00), this ), this takes takes OO((nn)) time time

V0 1 2 nr

V0 1 2 n

or

V0 1 2 nr

Algorithm remove(i)e A[i]for t = i to n-2 do

A[t] A[t+1]n n-1return e

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 88

PerformancePerformanceIn the array based implementation of an In the array based implementation of an Array ListArray List– The space used by the data structure is The space used by the data structure is OO((nn))– sizesize, , isEmptyisEmpty, , getget and and setset run in run in OO(1)(1) time time– addadd and and removeremove run in run in OO((nn)) time time

If we use the array in a circular fashion,If we use the array in a circular fashion, addadd(0)(0) and and removeremove(0)(0) run in run in OO(1)(1) time timeIn an In an addadd operation, when the array is operation, when the array is full, instead of throwing an exception, full, instead of throwing an exception, we can replace the array with a larger we can replace the array with a larger oneone

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 99

Growable Array-based ImplementationGrowable Array-based ImplementationConsider an array list Consider an array list implemented with arrayimplemented with arrayIn a In a addadd operation, when operation, when the array is full, instead of the array is full, instead of throwing an exception, we throwing an exception, we can replace the array with can replace the array with a larger onea larger oneHow large should the new How large should the new array be?array be?– incremental strategy: incremental strategy:

increase the size by a increase the size by a constant constant cc

– doubling strategy: doubling strategy: double the sizedouble the size

Algorithm add(i, o)if n = S.length 1 then

A new array ofsize …

for j 0 to i-1 do A[j] S[j]

A[i] = o;for ji+1 to n do

A[j] = S[j-1]; S A

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1010

Comparison of the StrategiesComparison of the StrategiesWe compare the incremental strategy and We compare the incremental strategy and the doubling strategy by analyzing the the doubling strategy by analyzing the total time total time TT((nn)) needed to perform a series needed to perform a series of of nn addadd operations operations

We assume that we start with an empty We assume that we start with an empty array list represented by an array of size array list represented by an array of size 11

We call amortized time of an We call amortized time of an addadd operation operation the average time taken by an the average time taken by an addadd over the over the series of operations, i.e., series of operations, i.e., TT((nn)/)/nn

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1111

Incremental Strategy Analysis Incremental Strategy Analysis We replace the array We replace the array k k = = nn//c c timestimesThe total time The total time TT((nn)) of a series of of a series of nn push push operations is proportional tooperations is proportional to

nn + + c c + + 22c c + 3+ 3c c + 4+ 4c c ++ … … + + kc kc ==nn + + cc(1 + 2 + 3 + … + (1 + 2 + 3 + … + kk) ) ==

nn + + ckck((k k + 1)/2+ 1)/2Since Since cc is a constant, is a constant, TT((nn)) is is OO((nn + + kk22)),, i.e., i.e., OO((nn22))The amortized time of an The amortized time of an addadd operation operation is is OO((nn))

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1212

Doubling Strategy AnalysisDoubling Strategy Analysis

We replace the array We replace the array k k = = loglog22 n n timestimesThe total time The total time TT((nn)) of a series of a series of of nn addadd operations is operations is proportional toproportional to

nn + + 1 + 2 + 4 + 8 + …+ 21 + 2 + 4 + 8 + …+ 2kk ==nn 2 2k k + 1+ 1 1 1 = = 22n n 11

TT((nn)) is is OO((nn))The amortized time of an The amortized time of an addadd operation is operation is OO(1)(1)

geometric series

1

2

14

8

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1313

Position ADT Position ADT The The PositionPosition ADT models the notion of ADT models the notion of place within a data structure where a place within a data structure where a single object is storedsingle object is storedIt gives a unified view of diverse ways It gives a unified view of diverse ways of storing data, such asof storing data, such as– a cell of an arraya cell of an array– a node of a linked lista node of a linked list

Just one method:Just one method:– object object elementelement(): returns the element (): returns the element

stored at the positionstored at the position

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1414

Node List ADTNode List ADT

The The Node ListNode List ADT ADT models a sequence models a sequence of positions storing of positions storing arbitrary objectsarbitrary objectsIt establishes a It establishes a before/after before/after relation between relation between positionspositionsGeneric methods:Generic methods:– sizesize(), (), isEmptyisEmpty()()

Accessor methods:Accessor methods:– firstfirst(), (), lastlast()()– prevprev(p), (p), nextnext(p)(p)

Update methods:Update methods:– setset(p, e) (p, e) – addBeforeaddBefore(p, e), (p, e),

addAftteraddAftter(p, e),(p, e),– addFirstaddFirst(e), (e),

addLastaddLast(e)(e)– removeremove(p)(p)

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1515

Doubly Linked ListDoubly Linked ListA doubly linked list provides a A doubly linked list provides a natural implementation of the natural implementation of the Node Node ListList ADT ADT

Nodes implement Position and store:Nodes implement Position and store:– elementelement– link to the previous nodelink to the previous node– link to the next nodelink to the next node

Special trailer and header nodesSpecial trailer and header nodes

prev next

elem

trailerheader nodes/positions

elements

node

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1616

InsertionInsertionWe visualize operation We visualize operation addAfteraddAfter(p, X), which returns (p, X), which returns position qposition q

A B X C

A B C

p

A B C

p

X

q

p q

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1717

Insertion AlgorithmInsertion AlgorithmAlgorithm addAlgorithm addAfter(After(p,ep,e):):

Create a new node Create a new node vvv.v.setElement(setElement(ee))v.v.setPrev(setPrev(pp)) {link {link v v to its predecessor}to its predecessor}v.v.setNext(setNext(p.p.getNext()) getNext()) {link {link v v to its successor}to its successor}((p.p.getNext())getNext())..setPrev(setPrev(vv) ) {link {link pp’s old successor to ’s old successor to vv}}p.p.setNext(setNext(vv)) {link {link p p to its new successor, to its new successor, vv}}return return vv {the position for the element {the position for the element ee}}

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1818

DeletionDeletionWe visualize We visualize removeremove(p), where p = (p), where p = lastlast()()

A B C D

p

A B C

D

p

A B C

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 1919

Deletion AlgorithmDeletion Algorithm

Algorithm Algorithm remove(remove(pp):):t t == p. p.elementelement {a temporary variable to hold {a temporary variable to hold the the return value}return value}((p.p.getPrev())getPrev())..setNext(setNext(p.p.getNext()) getNext()) {linking out {linking out pp}}((p.p.getNext())getNext())..setPrev(setPrev(p.p.getPrev())getPrev())p.p.setPrev(setPrev(nullnull)) {invalidating the position {invalidating the position pp}}p.p.setNext(setNext(nullnull))return return tt

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2020

PerformancePerformanceIn the implementation of the Node In the implementation of the Node List ADT by means of a doubly List ADT by means of a doubly linked listlinked list– The space used by a list with The space used by a list with nn

elements is elements is OO((nn))– The space used by each position of The space used by each position of

the list is the list is OO(1)(1)– All the operations of the List ADT run All the operations of the List ADT run

in in OO(1)(1) time time– Operation element() of the Operation element() of the

Position ADT runs in Position ADT runs in OO(1)(1) time time

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2121

Sequence ADT Sequence ADT The The SequenceSequence ADT is the ADT is the union of the Array List, union of the Array List, Deque, and Node List ADTsDeque, and Node List ADTs

Elements accessed byElements accessed by– index, orindex, or– PositionPosition

Generic methods:Generic methods:– sizesize(), (), isEmptyisEmpty()()

Bridge methods:Bridge methods:– atIndexatIndex(r)(r)– indexOfindexOf(p)(p)

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2222

Applications of SequencesApplications of Sequences

The Sequence ADT is a basic, general-The Sequence ADT is a basic, general-purpose, data structure for storing an purpose, data structure for storing an ordered collection of elementsordered collection of elements

Direct applications:Direct applications:– Generic replacement for stack, queue, vector, Generic replacement for stack, queue, vector,

or listor list– small database (e.g., address book)small database (e.g., address book)

Indirect applications:Indirect applications:– Building block of more complex data structuresBuilding block of more complex data structures

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2323

Multiple Inheritance in the Multiple Inheritance in the Sequence ADTSequence ADT

Sequence has three super Sequence has three super interfaces: Node List, Array interfaces: Node List, Array List, and DequeList, and Deque

Node List-based methods:Node List-based methods:– firstfirst() () – lastlast() () – prevprev(p)(p)– nextnext(p)(p)– setset(p, o)(p, o)– addBeforeaddBefore(p, o)(p, o)– addAfteraddAfter(p, o)(p, o)– addFirstaddFirst(o)(o)– addLastaddLast(o)(o)– removeremove(p)(p)

Array List-based methods:Array List-based methods:– getget(r)(r)– setset(r, o)(r, o)– addadd(r, o) (r, o) – removeremove(r)(r)

Deque-based methods:Deque-based methods:– addFirstaddFirst(o) (o) – addLastaddLast(o) (o) – removeFirstremoveFirst()()– removeLastremoveLast()()– getFirstgetFirst()()– getLastgetLast()()

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2424

Iterator ADT Iterator ADT An iterator abstracts the process of An iterator abstracts the process of scanning through a collection of elementsscanning through a collection of elementsMethods of the Iterator ADT:Methods of the Iterator ADT:– boolean boolean hasNext()hasNext()– object object next()next()Implementation with an array or singly Implementation with an array or singly linked listlinked listAn iterator is typically associated with an An iterator is typically associated with an another data structureanother data structureTwo notions of iterator:Two notions of iterator:– snapshot: freezes the contents of the data snapshot: freezes the contents of the data

structure at a given timestructure at a given time– dynamic: follows changes to the data structuredynamic: follows changes to the data structure

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2525

Design Pattern: Iterators Design Pattern: Iterators

We can augment the Stack, Queue, Vector, List We can augment the Stack, Queue, Vector, List and Sequence ADTs with the following method to and Sequence ADTs with the following method to iterate all elements:iterate all elements:– Iterator Iterator elements()elements()

For ADTs that support the notion of position, For ADTs that support the notion of position, such as list and sequences, we can provide a such as list and sequences, we can provide a method to iterate all positions:method to iterate all positions:– Iterator positions()

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2626

Iterators in Java Iterators in Java Java.util.Iterator interfaceJava.util.Iterator interfaceIterable ADT provides a method:Iterable ADT provides a method:– Iterator(): returns an iterator of the elements in the Iterator(): returns an iterator of the elements in the

collectioncollection

For-Each loopFor-Each loop– Syntax:Syntax:

forfor (type name: expression) (type name: expression)loop_statement;loop_statement;

– Equivalence:Equivalence:forfor (Iterator <type> it=expresion.iterator(); (Iterator <type> it=expresion.iterator();

it.hasNext();) it.hasNext();) {{

Type name = it.next();Type name = it.next();loop_statement;loop_statement;

}}

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2727

ListIterator ListIterator List iterator gives access to elements List iterator gives access to elements inside a linked list inside a linked list ListIterator protects the linked list ListIterator protects the linked list while giving access while giving access ListIterator encapsulates a position ListIterator encapsulates a position anywhere in the linked listanywhere in the linked list

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2828

Conceptual View of the ListIteratorConceptual View of the ListIterator Think of an iterator as pointing between two linksThink of an iterator as pointing between two links The The listIteratorlistIterator method of the method of the LinkedListLinkedList class gets a list class gets a list iteratoriterator

LinkedList list = . . . LinkedList list = . . . ListIterator iterator = list.listIterator();ListIterator iterator = list.listIterator();

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 2929

ListIterator Methods ListIterator Methods The The nextnext method moves the iterator method moves the iterator iterator.next();iterator.next();– nextnext throws a throws a NoSuchElementExceptionNoSuchElementException if you are if you are

already past the end of the listalready past the end of the listhasNexthasNext returns true if there is a next element returns true if there is a next element

if (iterator.hasNext())if (iterator.hasNext())iterator.next();iterator.next();

The The nextnext method returns the object of the link that it method returns the object of the link that it is passing is passing

while iterator.hasNext() while iterator.hasNext() { {

Object obj = iterator.next(); Object obj = iterator.next(); //do something with the object //do something with the object

}} To move the list position backwards, use: To move the list position backwards, use:

o hasPrevious hasPrevious o previousprevious

Lists and IteratorsLists and Iterators CSC311: Data StructuresCSC311: Data Structures 3030

Collections in JavaCollections in JavaCollectionCollectionIteratorIteratorListListListIteratorListIteratorMapMapQueueQueueSetSet