Sequences and Iterators - cs.mun.cayzchen/teaching/cs2711_2007w/notes/Sequences.… · Sequences...
Transcript of Sequences and Iterators - cs.mun.cayzchen/teaching/cs2711_2007w/notes/Sequences.… · Sequences...
Sequences 1/29/2007 10:41 AM
1
Sequences and Iterators 1© 2004 Goodrich, Tamassia
Sequences and Iterators
Sequences and Iterators 2© 2004 Goodrich, Tamassia
Sequence ADT (§ 6.4.3)The Sequence ADT is the union of the Vector and List ADTsElements accessed byn Index, orn Position
Generic methods:n size(), isEmpty()
Vector-based methods:n elemAtIndex(i),
replaceAtIndex(i, o), insertAtIndex(i, o), removeAtIndex(i)
List-based methods:n first(), last(), prev(p),
next(p), replace(p, o), insertBefore(p, o), insertAfter(p, o), insertFirst(o), insertLast(o), remove(p)
Bridge methods:n atIndex(i), indexOf(p)
Sequences 1/29/2007 10:41 AM
2
Sequences and Iterators 3© 2004 Goodrich, Tamassia
Applications of SequencesThe Sequence ADT is a basic, general-purpose, data structure for storing an ordered collection of elementsDirect applications:n Generic replacement for stack, queue, vector, or
listn small database (e.g., address book)
Indirect applications:n Building block of more complex data structures
Sequences and Iterators 4© 2004 Goodrich, Tamassia
Linked List ImplementationA doubly linked list provides a reasonable implementation of the Sequence ADTNodes implement Position and store:n elementn link to the previous noden link to the next node
Special trailer and header nodestrailerheader nodes/positions
elements
Position-based methods run in constant timeIndex-based methods require searching from header or trailer while keeping track of indices; hence, run in linear time
Sequences 1/29/2007 10:41 AM
3
Sequences and Iterators 5© 2004 Goodrich, Tamassia
Array-based ImplementationWe use a circular array storing positions A position object stores:n Elementn Index
Indices f and lkeep track of first and last positions
0 1 2 3
positions
elements
S
lf
Sequences and Iterators 6© 2004 Goodrich, Tamassia
Sequence Implementations
nninsertAtIndex, removeAtIndex11insertFirst, insertLast1ninsertAfter, insertBefore
n1replaceAtInex
11Replace
n1atIndex, indexOf, elemAtIndex
11size, isEmpty
1nremove
11first, last, prev, next
ListArrayOperation
Sequences 1/29/2007 10:41 AM
4
Sequences and Iterators 7© 2004 Goodrich, Tamassia
Iterators (§ 6.3)An iterator abstracts the process of scanning through a collection of elementsMethods of the IteratorADT:n boolean hasNext()n object next()
Extends the concept of Position by adding a traversal capabilityImplementation with an array or singly linked list
An iterator is typically associated with an another data structureWe can augment the Stack, Queue, Vector, List and Sequence ADTs with method:n Iterator iterator()
Potential extension of Iteratorn Backward traversal
w hasPrevious(), previous()n Mutation
w set(e), remove()