UCD Computer Science COMP-2001 1 Vectors, Lists and Sequence Stacks, queues, deques -- access elements only at the “ends” –Useful for applications that.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 24 Lists, Stacks, and Queues
Doubly Linked List This problem can be easily solved by using the double linked list. - Ed. 2 and 3.: Chapter 4 - Ed. 4: Chapter 3.
6/7/2014 8:24 AMSequences1 Lists and Sequences. 6/7/2014 8:24 AMSequences2 Outline and Reading Singly linked list Position ADT and List ADT (§5.2.1) Doubly.
Data Structures and Algorithms (60-254)
The Ranked Sequence ADT Definition A ranked sequence is a collection of items arranged in a linear order, where each item has a rank defining the relative.
© 2004 Goodrich, Tamassia Vectors1. © 2004 Goodrich, Tamassia Vectors2 The Vector ADT (“Vector” = “Array List” in §6.1) The Vector ADT extends the notion.
© 2004 Goodrich, Tamassia Sequences and Iterators1.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Stacks. 2 Outline and Reading The Stack ADT (§4.2.1) Applications of Stacks (§4.2.3) Array-based implementation (§4.2.2) Growable array-based stack.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Lists and Iterators (Chapter 6) COMP53 Oct 22, 2007.
Elementary Data Structures Stacks, Queues, & Lists Amortized analysis Trees.
CSC 212 Vectors, Lists, & Sequences. Announcement Daily quizzes accepted electronically only  Submit via one or other Dropbox  also accepted,
CSC401 – Analysis of Algorithms Lecture Notes 3 Basic Data Structures Objectives: Introduce basic data structures, including –Stacks –Queues –Vectors –Lists.
Sequences. The Sequence Abstract Data Type Implementing a Sequence.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5)
Vectors, Lists, and Sequences - Ed. 2 and 3.: Chapter 5 - Ed. 4: Chapter 6.
© 2004 Goodrich, Tamassia Vectors1 Lecture 03 Vectors, Lists and Sequences Topics Vectors Lists Sequences.
Chapter 6: Sequences : vectors and lists COL 106 Shweta Agrawal.
CSC 212 – Data Structures Lecture 21: IndexList a/k/a Vector, ArrayList.
Chapter 3: Arrays, Linked Lists, and Recursion
© 2004 Goodrich, Tamassia Sequences and Iterators1.
Stacks, Queues, and Deques
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures Using C++ 2E
Stacks and Linked Lists. Abstract Data Types (ADTs) An ADT is an abstraction of a data structure that specifies – Data stored – Operations on the data.
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
Data structures Abstract data types Java classes for Data structures and ADTs.
Iterators, Lists, and Sequences Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
© 2004 Goodrich, Tamassia Vectors1 Vectors and Array Lists.
Vectors, Lists, Sequences. Vectors Linear sequence s of n elements e rank – number of elements before e in s Vector supports access to elements via their.
Sequences1 Vectors Positions Lists General Sequences Bubble Sort Algorithm.
CSC 212 Sequences & Iterators. Announcements Midterm in one week  Will cover through chapter 5 of book  Midterm will be open book, open note (but, closed.
CS 367 Introduction to Data Structures Lecture 5.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Vectors, Lists, and Sequences. Vectors: Outline and Reading The Vector ADT (§6.1.1) Array-based implementation (§6.1.2)
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Lists1 © 2010 Goodrich, Tamassia. Position ADT  The Position ADT models the notion of place within a data structure where a single object is stored 
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
LINKED LISTS.
Chapter 2: Basic Data Structures. Spring 2003CS 3152 Basic Data Structures Stacks Queues Vectors, Linked Lists Trees Priority Queues and Heaps Dictionaries.
Lecture 6 of Computer Science II
Elementary Data Structures
Sequences and Iterators
Lists and Sequences 9/21/2018 7:21 PM Sequences Sequences
Sequences and Iterators
Vectors 11/29/2018 6:45 PM Vectors 11/29/2018 6:45 PM Vectors.
Lists and Sequences 12/8/2018 2:26 PM Sequences Sequences
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Recall What is a Data Structure Very Fundamental Data Structures
Vectors, Lists and Sequences
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Vectors, Lists, and Sequences
Vectors 4/26/2019 8:32 AM Vectors 4/26/2019 8:32 AM Vectors.
CS210- Lecture 6 Jun 13, 2005 Announcements
CS210- Lecture 7 Jun 14, 2005 Agenda Practice Session Vector
Stacks, Queues, and Deques
Vectors and Array Lists
Dynamic Array: Implementation of Stack
The Ranked Sequence ADT
Presentation transcript:

UCD Computer Science COMP Vectors, Lists and Sequence Stacks, queues, deques -- access elements only at the “ends” –Useful for applications that involve serially processing incoming data in some specific order Sequences, lists, vectors -- access elements in the “middle”, too –Useful for storing items that might be needed in any order Lectures

UCD Computer Science COMP The Vector ADT The rank of an item in a vector is a count of the number of items that occur before it: Seattle Rome Montreal Paris Vectors support the following methods: - size(), isEmpty()as usual -elemAtRank(r): Return the element with rank r; exception thrown if r<0 or r  size() -replaceAtRank(r,e): Replace the element at rank r with e and return the old element; exception thrown if r<0 or r  size() -insertAtRank(r,e):Insert a new element into S which will have rank r (and therefore ranks of subsequent elements will increase!); exception thrown if r<0 or r  size() -removeAtRank(r):Remove the element at rank r (and therefore ranks of subsequent elements will decrease); exception if r<0, r  size() Rank = “after” “before”

UCD Computer Science COMP Vector interface public interface Vector { public int size(); public boolean isEmpty(); public Object elemAtRank(int r) throws InvalidRankException; public Object replaceAtRank(int r, Object o) throws InvalidRankException; public void insertAtRank(int r, Object o) throws InvalidRankException; public Object removeAtRank(int r) throws InvalidRankException; }

UCD Computer Science COMP Implementing Vectors with Arrays public class ArrayVector implements Vector { … protected int N; // max capacity protected int n; // no. elements stored protected Object S[]; public ArrayVector(int capacity) { N = capacity; n = 0; S = new Object[N]; } … } used inactive … rank(S[i])  i

UCD Computer Science COMP Some pseudo code Algorithm insertAtRank(r,e): for i = n - 1, n - 2,..., r do S[i+1]  s[i] S[r]  e n  n + 1 Algorithm removeAtRank(r): e  S[r] for i = r, r + 1,..., n - 2 do S[i]  S[i + 1] n  n - 1 return e shift elements to the right in order to squeeze “e” in here shift elements left to fill the gap left by e here Algorithm elemAtRank(r): return S[r]; Algorithm replaceAtRank(r,e): x = elemAtRank(r); S[r]=e; return x; For simplicity, exception-throwing code not shown

UCD Computer Science COMP Array-Based Implementation (contd.) Time complexity of the various methods: Ouch! remember, O(1) means “constant” (independent of n)

UCD Computer Science COMP Problems with ArrayVector 1. As just mentioned, some methods are expensive [ O(n) complexity instead of O(1) ]; we’ll deal with this later 2. Predefined fixed capacity. One solution: “extendable (‘self-extending’) arrays”: if we ever run out of room, just create more!

UCD Computer Science COMP Extendable arrays 1. During initialization, use fixed capacity as before (either application-supplied argument or some default value) 2. When run out of room, allocate a new array of size (say) double the current size; copy over all the old elements to the new array 3. Carry on as before…. (4. Could also clean up wasted space if the vector is persistently under-capacity; but we won’t bother)

UCD Computer Science COMP ExtendableArrayVector class ExtendableArrayVector extends ArrayVector { // all we need to do is overload one method! public insertAtRank(int r, Object o) { if (n = = N) { // over capacity! N *= 2; Object S2[] = new Object[N]; for (int i=0; i<n; i++) S2[i]=S[i]; S = S2; } // now the original implementation does the job! super.insertAtRank(r,o); // call ArrayVector’s method } See “Vector” demo for complete details

UCD Computer Science COMP Linked-list implementation of Vector A second problem with the Array implementation is the need to slide elements during insert & remove -> causes O(n) [instead of O(1)] performance Sliding not needed if we use a doubly-linked list public class LinkedListVector implements Vector { private DLNode header; private DLNode trailer; public LinkedListVector() { header = new DLNode(null,null,null); trailer = new DLNode(null,header,null); header.setNext(trailer); } } …

UCD Computer Science COMP Vector Implementation with a Doubly Linked List 1. the list before insertion 2. creating a new node 3. after insertion:

UCD Computer Science COMP public void insertAtRank (int r, Object o) throws InvalidRankException { if (r size()) throw new InvalidRankException() DLNode next = nodeAtRank(r); // the new node will be right before ‘next’ DLNode prev = next.getPrev(); // the new node willl be right after ‘prev’ DLNode node = new DLNode(o, prev, next); // new node knows about its next & prev. Now // we tell next & prev about the new node. next.setPrev(node); prev.setNext(node); size++; } Some Java

UCD Computer Science COMP Deletion from Doubly Linked List the list before deletion: deleting a node after deletion:

UCD Computer Science COMP More Java public Object removeAtRank (int r) throws InvalidRankException { if (r size()-1) throw new InvalidRankException(); DLNode node = nodeAtRank(rank); // node to be removed DLNode next = node.getNext(); // node before node to be removed DLNode prev = node.getPrev(); // node after node to be removed prev.setNext(next); next.setPrev(prev); size--; return node.getElement(); // returns the element of the deleted node }

UCD Computer Science COMP One last Java detail… code for finding the node at a given rank r private DLNode nodeAtRank (int r) { DLNode node; // start at the node closest to the desired rank if (r <= size()/2) { //scan forward from header node = header.getNext(); for (int i=0; i < r; i++) node = node.getNext(); } else { // scan backward from trailer node = trailer.getPrev(); for (int i=0; i < size()-r-1 ; i++) node = node.getPrev(); } return node; } very common “pointer walking” expression either way, as many as n/2 iterations of this loop, therefore this method is O(n). Therefore….

UCD Computer Science COMP LinkedList Vector- Analysis Time complexity of the various methods: Ouch! O(n) Compare with slide #7 Oops, now all methods run slowly!

UCD Computer Science COMP Vector Summary Simple Vector ADT - access/remove elements by “rank” Leads to simple array-based implementation 2 problems: –Q1. Can we get unlimited capacity? - yes - use “extendable” array that creates more space on demand as needed –Q2. Can we avoid shifting elements during insert/remove? - ?? - linked lists save this shifting cost, but add new cost of needing to walk list to find elements by rank; overall, linked-list implementation is worse!

UCD Computer Science COMP Lists Lists are a generalization of Vectors: Instead of the “rank” of an element in a list; use the more generic notion of “position” of an element in a list The goal: ensure that access/insert/remove methods run in O(1) time! Lecture 14 the dog sat on my cat a list of 5 words position(the) is the first position position(cat) is the last position position(dog) is before position(sat) position(on) is after position(on)

UCD Computer Science COMP Position ADT Positions are very simple “helper” data-type One operation! element()returns the data-value element associated with the position (seem a bit like magic -- How can a Position possibly know?!?!! -- but it will all make sense soon…)

UCD Computer Science COMP List ADT size() & isEmpty() as usual… first()returns the Position of the first element throws InvalidPositionException if empty last()returns the Position of the last element throws InvalidPositionException if empty isFirst(p)is p the first position? isLast(p)is p the last position? before(p)return the Position immediately before p; throws InvalidPositionException if p is first after(p)return the Position immediately after p throws InvalidPositionException if p is last insertFirst(e)insert e at the first entry, and return the Position of this new first entry insertLast(e)insert e at the last entry, and return the Position of this new last entry insertBefore(p,e) insert e immediately before Position p and return Position object for e insertAfter(p,e) insert e immediately before Position p and return Position object for e remove(p)remove element at Position p; return the removed element Unlike ranks, note that Positions of ‘unaffected’ elements aren’t modified!

UCD Computer Science COMP Implementing Lists with Doubly Linked-Lists pages : class NodeList implements List Code in the book is somewhat more complicated than I’ve said so far –3 kinds of exceptions instead of 1 –Details like determining that a Position is “valid” (ie, a member of this ’s list, not some other list)

UCD Computer Science COMP Details interface Position { Object element(); } our linked lists will be built from node objects which will “double” as our Position objects: public class DNode implements Position { // page 199 // first, stuff related to Position private Object element; Object element() { return element; } // next, stuff related to linked list node private DNode next; private DNode prev; … }

UCD Computer Science COMP More details Why so complicated??!? Where went the distinction between abstract Positions and concrete Nodes?!!? The intent is that your application shouldn’t need to know that List is implemented using a linked list. But obviously there is a direct correspondence between Positions in the List abstraction, and nodes in the linked list implementation. So we’ll use a single class that serves both purposes, and use ‘private’ to prevent application for learning implementation-specific details. DNode inside NodeList implementation components for building linked lists your application your application can interpret these objects only as Positions

UCD Computer Science COMP NodeList analysis all List methods (first, last, isFirst, isLast, before, after, replaceElement, swapElements, insertFirst, insertLast, insertBefore, insertAfter, remove) O(1) Horray! All methods are fast (constant-time) However, what if our application needs both rank and position-based access. That’s where Sequence comes in…

UCD Computer Science COMP Sequences Sequence = Vector  List This week: - finish P6 - start P7 - finish Chapter 5 Next week: - finish P7 - start P8 - start Chapter 6 Lec 15

UCD Computer Science COMP Sequence Provides both rank- and position-based access, and “bridge” methods for converting between them the dog sat on my cat “dog” is in this position “cat” is in this position after rank “sat” is at rank 2“my” is at rank 4 (“bridge”)

UCD Computer Science COMP Sequence ADT Everything required for Vector and List, plus two new methods: –atRank(r)return the Position associated with the given rank –rankOf(p)return the rank associated with Position p

UCD Computer Science COMP Sequence Interface interface Sequence extends List, Vector { Position atRank(int r); int rankOf(Position p); } Multiple inheritance - this interface has two parents!?!?! Actually, Java permits only a very weak form: only interfaces can have multiple super-classes - ie, only “promises” can be inherited. Other languages (Lisp, C++, Smalltalk, …) allow classes to have multiple super-classes; ie, actual methods can be inherited from multiple parents.

UCD Computer Science COMP Interface vs class multiple inheritance interface X { int x(); String y(int a); void z(String u); } interface Y { String p(int a); double q(); void z(String u); } class C implements X, Y { … } C must implement all these methods; no problem promising z twice class X { int x() {…} String y(int a) {…} void z(String u) {…} } class Y { String p(int a) {…} double q() {…} void z(String u) {…} } class C extends X, Y { } C inherits all these methods… C c = … c.z(“fishfood”); which implementation of z should be called?!?!! …but

UCD Computer Science COMP Implementing Sequence with Doubly Linked List G&T page 208 class NodeSequence extends NodeList implements Sequence (why do we need to specify both extends and implements?) L14, pp Inherited from NodeList first, last, isFirst, isLast, before, after, replaceElement, swapElements, insertFirst, insertLast, insertBefore, insertAfter, remove Defined in NodeSequence (not inherited) atRank, rankOf, [next slide…] elementAtRank, [next slide…] insertAtRank, removeAtRank [p 208]

UCD Computer Science COMP NodeSequence [cont] bridge methods Position atRank(int rank) [see p 208 for Java] repeat: jump from header, to header.next, to header.next.next, …, until ‘rank’ nodes have been passed return currrent node int rankOf(Position p) repeat jump from from p to p.prev, to p.prev.prev, …, until header node is encountered return the number of nodes passed p atRank(2) both run in time O(n) !

UCD Computer Science COMP rankOf - Java int rankOf(Position p) { DNode n = (DNode) p; int rank = 0; while (n != header) { n = n.getPrev(); rank++; } return rank; } we know this Position is in fact a DNode, so this casting is OK

UCD Computer Science COMP NodeSequence [cont] With bridge methods in place, the methods required by Vector are very simple: [exception-handling code omitted for simplicity] Object elemAtRank(int rank) { return atRank(rank).element() } void insertAtRank(int rank, Object element) { insertBefore(atRank(rank), element); } Object removeAtRank(int rank) { return remove(atRank(rank)); } Object replaceAtRank(int rank, Object element) { return replaceElement(atRank(rank),element); } [see p 208 for details]

UCD Computer Science COMP Analysis of NodeSequence O(n) all List methods (first, last, isFirst, isLast, before, after, replaceElement, swapElements, insertFirst, insertLast, insertBefore, insertAfter, remove) Vector methods Slow because bridge method atRank is slow! O(1)

UCD Computer Science COMP Implementing Sequence with Array The ArrayList -vs- NodeList implementations of List suggest that linked-lists implementations are inherently slow for rank-based access, and array-based implements are inherently slow for position-based access. Is this O(n) -vs- O(1) tradeoff is inevitable? No … advanced data structures you’ll learn about in the future such as hash tables can give fast access in both cases… but they’re too complicated for now… As a suggestion of things to come… ArraySequence uses arrays instead of linked lists, but with a clever special ‘trick’ to improve complexity of some of the methods

UCD Computer Science COMP ArraySequence - naïve version class ArrayPosition implements Position{ Object A[]; index i; ArrayPosition(Object[] B, int j) {A=B; I=j;} Object element() {return A[i];} } A:  i: 3 the dog sat on my cat ArrayPosition object for “on” A:  i: 1 ArrayPosition object for “dog”

UCD Computer Science COMP ArraySequence: inserting an element A:  i: 3 the dog sat on my cat A:  i: 0 A:  i: 2 A:  i: 4 A:  i: 5 A:  i: 6 Sequence s = new ArraySequence(); … other elements inserted … Position p = s.insertLast(“cat”); s.insertBefore(p, “fat”); p These ArrayPositions Aren’t stored in the ArraySequence; the application must store them for later use.

UCD Computer Science COMP Insertion, continued A:  i: 2 the dog sat on my cat A:  i: 0 A:  i: 1 A:  i: 3 A:  i: 4 A:  i: 5 p Slide existing elements (just like ArrayVector.insertAtRank) A:  i:2 the dog sat on my fat cat A:  i: 0 A:  i: 1 A:  i: 3 A:  i: 4 A:  i: 5 A:  i: 5 Yikes! Need to increment ranks… But how??!?!

UCD Computer Science COMP ArraySequence.insertAtRank Algorithm insertBefore(Position p, Object o) –For r = size(), size()-1, …, rankOf(p)+2, rankOf(p)+1: A[r] = A[r-1]; –A[r] = o; –size++ –// yikes! We need to update Positions corresponding to ranks #size down to #rankOf(p)+1 -- but the ArraySequence doesn’t keep a list of the Positions -- that’s the application’s responsibility! –Return new ArrayPosition(A,r); This naïve approach doesn’t work!!

UCD Computer Science COMP Sequences, continued Where are we? Vector - rank-based access array-based implementation - insert/remove are slow linked-list implementation - all methods slow! List - position-based access linked-list implementation - all methods fast! Sequence - both kinds of access linked-list implementation - as before, rank-based methods are slow started array-based implementation but hit dead-end to do: a better array-based implementation L16

UCD Computer Science COMP ArraySequence: Cleverer approach class ArrayPosition implements Position { int rank; Object element; ArrayPosition(int r, Object e) {rank=r; element=e;} Object element() {return element;} } element: “the” rank: element: “dog” rank: 1 element: “sat” rank: 2 element: “on” rank: 3 element: “my” rank: 4 element: “cat” rank: 5

UCD Computer Science COMP Cleverer ArraySequence Still need to shift elements during insert/remove. But now… since the SequenceArray “remembers” the ArrayPositions it has “exported” to the application, there’s no problem to modify the ranks of the moved elements.

UCD Computer Science COMP ArraySequence vs NodeSequence: Analysis OperationArrayNode size, isEmptyO(1)O(1) atRank, rankOf, elemAtRankO(1)O(n) first, last, before, afterO(1)O(1) replaceElement, swapElementsO(1)O(1) replaceAtRankO(1)O(n) insertAtRank, removeAtRankO(n)O(n) insertFirst, insertLastO(1)O(1) insertAfter, insertBeforeO(n)O(1) removeO(n)O(1) There’s no free lunch… If you need these operations, use ArraySequence If you need these operations, use NodeSequence

UCD Computer Science COMP Application example: Sorting Sorting: Given some sequence (Sally, John, Dave, Ellen, Pat), output a permutation of the elements in order (Dave, Ellen, John, Pat, Sally) Dozens of algorithms; person-centuries of research Well known result: the fastest possible sorting algorithm runs in time O(n · log n) to sort n items A very simple algorithm: Bubble Sort - O(n 2 ) The point isn’t to build a great algorithm, but to show how the Sequence ADT might be used in practice

UCD Computer Science COMP Bubble sort First pass: Start at top, compare adjacent pairs, swap larger toward bottom if needed At the end of the first pass, largest element is guaranteed to be at bottom 2nd pass: Start at top, compare adjacent pairs, swap larger toward bottom if needed At the end of the 2nd pass, 2nd-largest element is guaranteed to be at 2nd-from-bottom rd pass (no swaps needed) 4th pass (no swaps needed) done

UCD Computer Science COMP Bubble-sort using ranks void bubbleSort(Sequence S) { int n = S.size(); for (int i = 0; i valAtRank(S,j)) S.swapElements(S.atRank(j-1), S.atRank(j)); } int valAtRank(Sequence S, int i) { return ((Integer) S.elemAtRank(i)).intValue(); } Assume S contains Integer objects

UCD Computer Science COMP Bubble-sort using positions void bubbleSort(Sequence S) { int n = S.size(); for (int i = 0; i<n; i++) { // i’th pass Position prec = S.first(), succ; for (int j = 1; j<n-i; j++) { succ = S.after(prec); if (valAtPos(prec) > valAtPos(succ)) S.swapElements(prec,succ); prec = succ; } int valAtPos(Position p) { return ((Integer) p.element()).intValue(); }

UCD Computer Science COMP Iterators A common operation on a sequence is to perform some operation on each item in turn. –Print out each element, add 1 to each element in a list of integers, remove spaces from each element in a list of strings, … Iterator (also known as Enumerator) is an ADT encapsulating this notion of “walking along the elements of a list”. Two operations: –hasNext() Are there more items? –nextObject()Returns next object (if there is one)

UCD Computer Science COMP SequenceIterator interface ObjectIterator { boolean hasNext(); Object nextIterator(); } class SequenceIterator implements ObjectIterator { Sequence S; // the sequence over which we’re iterating DNode node; // current position in S SequenceIterator(Sequence _S) { S = _S; node = (DNode) S.first(); } boolean hasNext() { return node != S.trailer; } Object nextObject() { Object o = node.element(); node = node.getNext(); return o; } }

UCD Computer Science COMP Iterator: example Now you can say… Sequence S = … SequenceIterator si = new SequenceIterator(S); while (si.hasNext()) { System.out.println(si.nextObject() + “, “); }

UCD Computer Science COMP Iterators in java Java has built-in iterators for java.util.Vector (Actually, a variety of iterators for all of the varied/complicated kinds of “containers”) Import java.util.*; … Vector v = … Iterator i = v.iterator(); while (i.hasNext()) { System.out.println(i.next()); }

UCD Computer Science COMP Lec 7 - Lec 16 - Summary Container size, isEmpty Stack push, pop Queue enqueue, dequeue Deque Vector insertAtRank, … List insertBefore, … Sequence rankOf, atRank ADTs Implementation techniques Array extendable array Linked lists doubly-linked lists Positions vs array indices Complexity results expose tradeoffs between requirements of ADTs and efficiency of implementation