Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Stacks
INFO0902 – Data Structures and
Algorithms
Basic ADTs: stacks, queues, array
lists, node list, sequences, iterators
Justus H. Piater
The Stack ADT (stack, LIFO)
Java Interface
void push(Object e);
/**
* Interface for a stack: a collection of objects that are inserted
* and removed according to the last–in first–out principle.
*
* @author Roberto Tamassia
* @author Michael Goodrich
* @see EmptyStackException
*/
Object pop(void);
Integer size(void);
Boolean isEmpty(void);
public interface Stack {
/**
* Return the number of elements in the stack.
* @return number of elements in the stack.
*/
public int size();
/**
* Return whether the stack is empty.
* @return true if the stack is empty, false otherwise.
*/
Object top(void);
Applications?
Stacks
3 / 83
Stacks
4 / 83
Java Interface (Continued)
Errors
pop() and top() raise an error if the stack is empty:
public boolean isEmpty();
/**
* Inspect the element at the top of the stack.
* @return top element in the stack.
* @exception EmptyStackException if the stack is empty.
*/
public Object top() throws EmptyStackException;
/**
* Insert an element at the top of the stack.
* @param element element to be inserted.
*/
public void push (Object element);
/**
* Remove the top element from the stack.
* @return element removed.
* @exception EmptyStackException if the stack is empty.
*/
public Object pop() throws EmptyStackException;
}
Stacks
/**
* Runtime exception thrown when one tries to perform operation top or
* pop on an empty stack.
*/
public class EmptyStackException extends RuntimeException {
public EmptyStackException(String err) {
super(err);
}
}
5 / 83
Implementation: Array
Stacks
6 / 83
Implementation: Array (Continued)
Algorithm size():
return
error
return
Algorithm isEmpty():
return
Algorithm top():
if isEmpty() then
error
return
Algorithm push( ):
if size()
then
error
Algorithm pop():
if isEmpty() then
Stacks
7 / 83
Stacks
8 / 83
Complexity
Java Implementation
• Time:
• Space:
/**
* Implementation of the Stack interface using a fixed–length array.
* An exception is thrown if a push operation is attempted when the
* size of the stack is equal to the length of the array.
*
* @author Natasha Gelfand
* @author Roberto Tamassia
* @see FullStackException
*/
public class ArrayStack implements Stack {
/**
* Default length of the array used to implement the stack.
*/
public static final int CAPACITY = 1000;
/**
* Length of the array used to implement the stack.
*/
protected int capacity;
Stacks
9 / 83
Java Implementation (Continued)
Stacks
Java Implementation (Continued)
public ArrayStack(int cap) {
capacity = cap;
stack = new Object[capacity];
}
/**
* O(1) time.
*/
public int size() {
return (top + 1);
}
/**
* O(1) time.
*/
public boolean isEmpty() {
return (top < 0);
}
/**
* O(1) time.
* @exception FullStackException if the array is full.
/**
* Array used to implement the stack.
*/
protected Object stack[];
/**
* Index of the top element of the stack in the array.
*/
protected int top = –1;
/**
* Initialize the stack to use an array of default length CAPACITY.
*/
public ArrayStack() {
this(CAPACITY);
}
/**
* Initialize the stack to use an array of given length.
*
* @param cap length of the array.
*/
Stacks
10 / 83
11 / 83
Stacks
12 / 83
Java Implementation (Continued)
if (isEmpty())
throw new EmptyStackException("Stack is Empty.");
elem = stack[top];
stack[top––] = null; // dereference stack[top] for garbage collection.
return elem;
}
}
*/
public void push(Object obj) throws FullStackException {
if (size() == capacity)
throw new FullStackException("Stack overflow.");
stack[++top] = obj;
}
/**
* O(1) time.
*/
public Object top() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException("Stack is empty.");
return stack[top];
}
/**
* O(1) time.
*/
public Object pop() throws EmptyStackException {
Object elem;
Stacks
13 / 83
Application: Reverse an Array
Stacks
14 / 83
Application: Matching Parentheses
public static Integer[] reverse(Integer[] a) {
Stack stack = new ArrayStack(a.length);
Integer[] b = new Integer[a.length];
Algorithm parenMatch( , ):
Input: a string of parentheses of different types.
Output: true if all the parentheses match, false otherwise.
empty stack
for
to
do
if
is a left parenthesis then
.push( )
else
if .isEmpty() then
return false
if .pop() does not match
then
return false
if .isEmpty() then
return true
else
return false
for (int i=0; i < a.length; i++)
stack.push(a[i]);
for (int i=0; i < a.length; i++)
b[i] = (Integer) (stack.pop());
return b;
}
Stacks
Java Implementation (Continued)
15 / 83
Stacks
16 / 83
The Queue ADT (file, FIFO)
Queues
void enqueue(Object e);
Object dequeue(void);
Integer size(void);
Boolean isEmpty(void);
Object front(void);
Applications?
Queues
Java Interface
Java Interface (Continued)
public interface Queue {
/**
* Returns the number of elements in the queue.
* @return number of elements in the queue.
*/
public int size();
/**
* Returns whether the queue is empty.
* @return true if the queue is empty, false otherwise.
*/
public boolean isEmpty();
/**
* Inspects the element at the front of the queue.
* @return element at the front of the queue.
* @exception EmptyQueueException if the queue is empty.
*/
public Object front() throws EmptyQueueException;
/**
* Inserts an element at the rear of the queue.
Queues
18 / 83
* @param element new element to be inserted.
*/
public void enqueue (Object element);
/**
* Removes the element at the front of the queue.
* @return element removed.
* @exception EmptyQueueException if the queue is empty.
*/
public Object dequeue() throws EmptyQueueException;
}
19 / 83
Queues
20 / 83
Implementation: Simple Array
Implementation: Circular Array
Algorithm size():
return
mod
Algorithm isEmpty():
return
Algorithm front():
if isEmpty() then
error
return
Algorithm dequeue():
if isEmpty() then
error
return
mod
Algorithm enqueue(o):
Queues
21 / 83
if size()
error
Implementation: Circular Array (Continued)
22 / 83
Complexity
• Time:
• Space:
then
mod
Queues
Queues
23 / 83
Queues
24 / 83
Linked List DS
Linked Lists
Useful to avoid arbitrary capacity limits.
The list is identified by the head pointer.
Each node contains the element and next pointers.
A null next pointer indicates the end of the list.
Linked Lists
A Node in Java
A Node in Java (Continued)
public class Node {
// Instance variables:
private Object element;
private Node next;
/** Creates a node with null references to its element and next node. */
public Node() {
this(null, null);
}
/** Creates a node with the given element and next node. */
public Node(Object e, Node n) {
element = e;
next = n;
}
// Accessor methods:
public Object getElement() {
return element;
}
public Node getNext() {
return next;
Linked Lists
26 / 83
27 / 83
}
// Modifier methods:
public void setElement(Object newElem) {
element = newElem;
}
public void setNext(Node newNext) {
next = newNext;
}
}
Linked Lists
28 / 83
Complexity
•
•
•
•
Implementing a Stack
Space:
Insertion and removal at the head:
Insertion and removal at the tail:
Ditto, with additional tail pointer:
Linked Lists
Complexity of the operations?
public class NodeStack implements Stack {
protected Node top; // reference to the head node
protected int size; // number of elements in the stack
public NodeStack() { // constructs an empty stack
top = null;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
if (top == null)
return true;
return false;
}
public void push(Object elem) {
Node v = new Node(elem, top); // create and link–in a new node
29 / 83
Linked Lists
Implementing a Stack (Continued)
Implementing a Queue
Complexity of the operations?
top = v;
size++;
}
public Object top() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException("Stack is empty.");
return top.getElement();
}
public Object pop() throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException("Stack is empty.");
Object temp = top.getElement();
top = top.getNext(); // link–out the former top node
size––;
return temp;
}
}
Linked Lists
30 / 83
Why not the other way around?
public void enqueue(Object obj) {
Node node = new Node();
node.setElement(obj);
node.setNext(null); // node will be new tail node
if (size == 0)
head = node; // special case of a previously empty queue
else
tail.setNext(node); // add node at the tail of the list
tail = node; // update the reference to the tail node
size++;
}
public Object dequeue() throws EmptyQueueException {
if (size == 0)
throw new EmptyQueueException("Queue is empty.");
Object obj = head.getElement();
31 / 83
Linked Lists
32 / 83
Implementing a Queue (Continued)
Deques
head = head.getNext();
size––;
if (size == 0)
tail = null; // the queue is now empty
return obj;
}
Linked Lists
33 / 83
The Deque ADT (double-ended queue)
The Deque ADT (double-ended queue) (Continued)
Applications?
void insertFirst(Object e);
void insertLast(Object e);
Object removeFirst(void);
Object removeLast(void);
Integer size(void);
Boolean isEmpty(void);
Object first(void);
Object last(void);
Generalization of both the stack and the queue.
Deques
35 / 83
Deques
36 / 83
Doubly Linked List DS
Sentinel Nodes
All insertions and removals are done in the same way,
including at the head and at the tail.
public class DLNode {
private Object element;
private DLNode next, prev;
DLNode() { this(null, null, null); }
DLNode(Object e, DLNode p, DLNode n) {
element = e;
next = n;
prev = p;
}
public void setElement(Object newElem) { element = newElem; }
public void setNext(DLNode newNext) { next = newNext; }
public void setPrev(DLNode newPrev) { prev = newPrev; }
public Object getElement() { return element; }
public DLNode getNext() { return next; }
public DLNode getPrev() { return prev; }
}
Deques
37 / 83
Deques
Implementing a Deque using a Doubly Linked List
Implementing a Deque using a
Doubly Linked List (Continued)
public class NodeDeque implements Deque {
protected DLNode header, trailer; // sentinels
protected int size; // number of elements
public NodeDeque() { // initialize an empty deque
header = new DLNode();
trailer = new DLNode();
header.setNext(trailer); // make header point to trailer
trailer.setPrev(header); // make trailer point to header
size = 0;
}
public Object first() throws EmptyDequeException {
if (isEmpty())
throw new EmptyDequeException("Deque is empty.");
return header.getNext().getElement();
}
public void insertFirst(Object o) {
DLNode second = header.getNext();
DLNode first = new DLNode(o, header, second);
second.setPrev(first);
Deques
38 / 83
header.setNext(first);
size++;
}
public Object removeLast() throws EmptyDequeException {
if (isEmpty())
throw new EmptyDequeException("Deque is empty.");
DLNode last = trailer.getPrev();
Object o = last.getElement();
DLNode secondtolast = last.getPrev();
trailer.setPrev(secondtolast);
secondtolast.setNext(trailer);
size––;
return o;
}
39 / 83
Deques
40 / 83
The Array List ADT
Array Lists
Abstraction of an array: access by rank ,
etc.,
,
Object elemAtRank(Integer r);
Object replaceAtRank(Integer r, Object e);
void insertAtRank(Integer r, Object e);
Object removeAtRank(Integer r);
Array Lists
Java Interface
Implementing a Deque
using an Array List
public interface ArrayList {
/** Returns the number of elements in the vector. */
public int size();
/** Returns whether the vector is empty. */
public boolean isEmpty();
/** Returns the element stored at the given rank. */
public Object elemAtRank(int r)
throws BoundaryViolationException;
/** Replaces the element stored at the given rank. */
public Object replaceAtRank(int r, Object e)
throws BoundaryViolationException;
/** Inserts an element at the given rank. */
public void insertAtRank(int r, Object e)
throws BoundaryViolationException;
/** Removes the element stored at the given rank. */
public Object removeAtRank(int r)
throws BoundaryViolationException;
}
Array Lists
42 / 83
43 / 83
Array Lists
44 / 83
Implementation by
a Fixed-Size Array
Java Implementation
Complexity of the four functions in terms of :
Complexity of the four functions in terms of
Insertions and removals at
in
/** Realization of a vector by means of an array. The array has
* initial length 16 and is doubled when the size of the vector
* exceeds the capacity of the array. No shrinking of the array is
* performed.
*/
public class ArrayVector implements Vector {
private Object[] A;
// array storing the elements of the vector
private int capacity = 16; // initial length of array A
private int size = 0;
// number of elements stored in the vector
/** Creates the vector with initial capacity 16. */
public ArrayVector() { A = new Object[capacity]; }
/** Inserts an element at the given rank. */
public void insertAtRank(int r, Object e)
throws BoundaryViolationException {
checkRank(r, size() + 1);
if (size == capacity) {
// an overflow
capacity *= 2;
Object[] B = new Object[capacity];
for (int i=0; i<size; i++)
and :
?
Array Lists
45 / 83
Array Lists
Java Implementation (Continued)
Implementation using an Extensible Array
Whenever an insertion would exceed the array
capacity, it is replaced by another array of twice the
size.
B[i] = A[i];
A = B;
}
for (int i=size–1; i>=r; i––)
// shift elements up
A[i+1] = A[i];
A[r] = e;
size++;
}
/** Removes the element stored at the given rank. */
public Object removeAtRank(int r)
throws BoundaryViolationException {
checkRank(r, size());
Object temp = A[r];
for (int i=r; i<size–1; i++)
// shift elements down
A[i] = A[i+1];
size––;
return temp;
}
Array Lists
46 / 83
Proposition: The total time to insert
the end of the array is
.
elements at
Proof (by amortization): • Suppose that the th augmentation costs
• Overcharge each insertion by 2 Euros.
• These Euros will pay for the augmentation.
47 / 83
Array Lists
Euros.
48 / 83
Implementation using an
Additive Extensible Array
java.util.ArrayList
and java.util.Vector
ADT Array List
When an insertion would exceed the array capacity,
it is replaced by another array larger by a constant
increment.
Proposition: The total time to insert
the end of the array is
.
size(), isEmpty()
elemAtRank( )
replaceAtRank( , )
insertAtRank( , )
removeAtRank( )
elements at
Proof: The insertions give rise to
augmentations. Thus, the time required to insert all
elements is proportional to
Array Lists
49 / 83
Java ArrayList and
Vector
size(), isEmpty()
get( )
set( , )
add( , )
remove( )
Array Lists
50 / 83
The Node List ADT
Node Lists
Abstraction of a list: access by position; notions of
preceding and following elements (but no absolute
ranks)
Position:
Object element(void);
Node List:
Position first(void);
Position last(void);
Position prev(Position p);
Position next(Position p);
Node Lists
52 / 83
The Node List ADT (Continued)
Error Conditions
•
•
•
•
•
Object replace(Position p, Object e);
Position insertFirst(Object e);
Position insertLast(Object e);
Position insertBefore(Position p, Object e);
null
has been removed from the list
belongs to a different list
is the first position, and we call prev( )
is the last position, and we call next( )
Which error checks would you perform?
Position insertAfter(Position p, Object e);
Object remove(Position p);
Applications?
Node Lists
53 / 83
Node Lists
Java Interface
Java Interface (Continued)
public interface Position {
/** Returns the element stored at this position. */
Object element();
}
/** Inserts an element at the front of the list. */
public Position insertFirst(Object e);
/** Inserts and element at the back of the list. */
public Position insertLast(Object e);
/** Inserts an element after the given node in the list. */
public Position insertAfter(Position p, Object e)
throws InvalidPositionException;
/** Inserts an element before the given node in the list. */
public Position insertBefore(Position p, Object e)
throws InvalidPositionException;
/** Removes a node from the list. */
public Object remove(Position p)
throws InvalidPositionException;
/** Replaces the element stored at the given node. */
public Object replace(Position p, Object e)
throws InvalidPositionException;
}
public interface PositionList {
/** Returns the number of elements in this list. */
public int size();
/** Returns whether the list is empty. */
public boolean isEmpty();
/** Returns the first node in the list. */
public Position first();
/** Returns the last node in the list. */
public Position last();
/** Returns the node after a given node in the list. */
public Position next(Position p)
throws InvalidPositionException, BoundaryViolationException;
/** Returns the node before a given node in the list. */
public Position prev(Position p)
throws InvalidPositionException, BoundaryViolationException;
Node Lists
54 / 83
55 / 83
Node Lists
56 / 83
Doubly Linked List: insert
and remove an element
Java Implementation: DNode
Algorithm insertAfter( , ):
create a new node
.setElement( )
.setPrev( )
.setNext( .getNext())
.getNext().setPrev( )
.setNext( )
return
public class DNode implements Position {
private DNode prev, next; // References to the nodes before and after
private Object element; // Element stored in this position
// Constructor
public DNode(DNode newPrev, DNode newNext, Object elem) {
prev = newPrev;
next = newNext;
element = elem;
}
// Method from interface Position
public Object element() throws InvalidPositionException {
if ((prev == null) && (next == null))
throw new InvalidPositionException("Position is not in a list!");
return element;
}
// Accessor methods
public DNode getNext() { return next; }
public DNode getPrev() { return prev; }
// Update methods
Algorithm remove( ):
.getPrev().setNext( .getNext())
.getNext().setPrev( .getPrev())
return .element
Node Lists
57 / 83
Java Implementation:
DNode (Continued)
public void setNext(DNode newNext) { next = newNext; }
public void setPrev(DNode newPrev) { prev = newPrev; }
public void setElement(Object newElement) { element = newElement; }
}
Node Lists
59 / 83
Node Lists
58 / 83
Java Implementation:
Doubly-Linked List
public class NodePositionList implements PositionList {
protected int numElts;
// Number of elements in the list
protected DNode header, trailer;
// Special sentinels
/** Constructor that creates an empty list; O(1) time */
public NodeList() {
numElts = 0;
header = new DNode(null, null, null);
// create header
trailer = new DNode(header, null, null); // create trailer
header.setNext(trailer); // make header and trailer point to each other
}
/** Checks if position is valid for this list and converts it to
* DNode if it is valid; O(1) time */
protected DNode checkPosition(Position p) throws InvalidPositionExceptio
if (p == null)
throw new InvalidPositionException
("Null position passed to NodeList");
if (p == header)
throw new InvalidPositionException
("The header node is not a valid position");
Node Lists
60 / 83
Java Implementation: Doubly-Linked List (Continued)
Java Implementation: Doubly-Linked List (Continued)
if (p == trailer)
throw new InvalidPositionException
("The trailer node is not a valid position");
try {
DNode temp = (DNode)p;
if ((temp.getPrev() == null) || (temp.getNext() == null))
throw new InvalidPositionException
("Position does not belong to a valid NodeList");
return temp;
} catch (ClassCastException e) {
throw new InvalidPositionException
("Position is of wrong type for this list");
}
}
/** Returns the number of elements in the list; O(1) time */
public int size() { return numElts; }
/** Returns whether the list is empty; O(1) time */
public boolean isEmpty() { return (numElts == 0); }
/** Returns the first position in the list; O(1) time */
Node Lists
public Position first()
throws EmptyListException {
if (isEmpty())
throw new EmptyListException("List is empty");
return header.getNext();
}
/** Returns the position before the given one; O(1) time */
public Position prev(Position p)
throws InvalidPositionException, BoundaryViolationException {
DNode v = checkPosition(p);
DNode prev = v.getPrev();
if (prev == header)
throw new BoundaryViolationException
("Cannot advance past the beginning of the list");
return prev;
}
/** Insert the given element before the given position, returning
* the new position; O(1) time */
public Position insertBefore(Position p, Object element)
61 / 83
Java Implementation: Doubly-Linked List (Continued)
throws InvalidPositionException {
//
DNode v = checkPosition(p);
numElts++;
DNode newNode = new DNode(v.getPrev(), v, element);
v.getPrev().setNext(newNode);
v.setPrev(newNode);
return newNode;
}
/** Insert the given element at the beginning of the list, returning
* the new position; O(1) time */
public Position insertFirst(Object element) {
numElts++;
DNode newNode = new DNode(header, header.getNext(), element);
header.getNext().setPrev(newNode);
header.setNext(newNode);
return newNode;
}
/**Remove the given position from the list; O(1) time */
public Object remove(Position p)
Node Lists
63 / 83
Node Lists
62 / 83
Java Implementation: Doubly-Linked List (Continued)
throws InvalidPositionException {
DNode v = checkPosition(p);
numElts––;
DNode vPrev = v.getPrev();
DNode vNext = v.getNext();
vPrev.setNext(vNext);
vNext.setPrev(vPrev);
Object vElem = v.element();
// unlink the position from the list and make it invalid
v.setNext(null);
v.setPrev(null);
return vElem;
}
/** Replace the element at the given position with the new element
* and return the old element; O(1) time */
public Object replace(Position p, Object element)
throws InvalidPositionException {
DNode v = checkPosition(p);
Node Lists
64 / 83
Java Implementation: Doubly-Linked List (Continued)
Sequences
Object oldElt = v.element();
v.setElement(element);
return oldElt;
}
Node Lists
65 / 83
The Sequence ADT
Java Interface
Union of array list and node list, plus the following
bridge functions:
/**
* An interface for a sequence, a data structure supporting all
* operations of a vector and a list.
*/
public interface Sequence extends List, Vector {
/** Returns the position containing the element at the given rank. */
public Position atRank(int r) throws BoundaryViolationException;
/** Returns the rank of the element stored at the given position. */
public int rankOf(Position p) throws InvalidPositionException;
}
Position atRank(Integer r);
Integer rankOf(Position p);
Sequences
67 / 83
Sequences
68 / 83
Implementation using
a Doubly-Linked List
Java Implementation
Complexity of the array list, node list and bridge
functions?
Sequences
/** Implementation of a sequence by means of a doubly linked list. */
public class NodeSequence extends NodeList implements Sequence {
/** Checks whether the given rank is in the range [0, n – 1] */
protected void checkRank(int r, int n)
throws BoundaryViolationException {
if (r < 0 || r >= n)
throw new BoundaryViolationException("Illegal rank: " + r);
}
/** Returns the position containing the element at the given rank;
* O(n) time. */
public Position atRank (int rank) {
DNode node;
checkRank(rank, size());
if (rank <= size()/2) { // scan forward from the head
node = header.getNext();
for (int i=0; i < rank; i++) node = node.getNext();
}
else { // scan backward from the tail
node = trailer.getPrev();
69 / 83
Java Implementation (Continued)
70 / 83
Implementation using an Array
Note
for (int i=1; i < size()–rank; i++)
node = node.getPrev();
}
return node;
}
/** Inserts an element at the given rank; O(n) time. */
public void insertAtRank (int rank, Object element)
throws BoundaryViolationException {
checkRank(rank, size() + 1);
if (rank == size()) insertLast(element);
else
insertBefore(atRank(rank), element);
}
/** Removes the element stored at the given rank; O(n) time. */
public Object removeAtRank (int rank)
throws BoundaryViolationException {
checkRank(rank, size());
return remove(atRank(rank));
}
Sequences
Sequences
We need to implement the Position ADT.
Complexity of the array list, node list and bridge
functions?
71 / 83
Sequences
72 / 83
Example: The Favorite List ADT
Two Implementations
Store in a list the elements accessed and their access
counts
• Sorted list
• Move-to-front heuristic
void access(Object e);
Complexity of the three functions in the following
scenario:
Object remove(Object e);
1.
2.
3.
4.
List top(Integer k);
Sequences
73 / 83
accesses of element 1
accesses of element 2
…
accesses of element Sequences
74 / 83
The Iterator ADT
Iterators
To traverse all elements of a collection, independently
of its implementation
Boolean hasNext(void);
Object next(void);
Such a collection must provide the following function:
Iterator elements(void);
Iterators
76 / 83
Usage in Java
Position Iterator
For node lists and sequences, it can be useful to iterate
over positions.
public static void printContainer(Iterable container) {
for (java.util.Iterator iter = contaner.iterator();
iter.hasNext();
System.out.println(iter.next());
}
next() returns a Position instead of an Object.
To obtain a position iterator, use positions() instead of
elements().
public static void printContainer(Iterable container) {
for (Object obj : container)
System.out.println(obj);
}
Iterators
77 / 83
Implementing a Position Iterator for the NodePositionList class
public class PositionIterator implements Iterator {
protected List list; // the underlying list
protected Position cur; // the current (next) position
public PositionIterator() { } // default constructor
public PositionIterator(List L) { // preferred constructor
list = L;
if (list.isEmpty()) cur = null; // list is empty
else cur = list.first(); // start with the first position
}
public boolean hasNext() { return (cur != null); }
public Object next() throws NoSuchElementException {
if (!hasNext()) throw new NoSuchElementException("No next position");
Position toReturn = cur;
if (cur == list.last()) cur = null; // no positions left
else cur = list.next(cur); // move cursor to the next position
return toReturn;
}
}
Iterators
79 / 83
Iterators
78 / 83
And Finally…
To the NodePositionList class we need to add:
/** Returns an iterator of all the nodes in the list. */
public Iterator positions() { return new PositionIterator(this); }
/** Returns an iterator of all the elements in the list. */
public Iterator elements() { return new ElementIterator(this); }
Iterators
80 / 83
Iterators in Java
Summary
See java.util.Iterator. (There is also an older
java.util.Enumeration, whose use is discouraged.)
The Java collections do not expose “positions”, but the
java.util.ListIterator provides equivalent functionality.
Iterators
81 / 83
Summary
We recalled some fundamental algorithmic concepts:
ADT:
• stack + queue = deque
• array list + node list = sequence
DS:
• simple and circular arrays
• extensible arrays
• singly and doubly linked lists
Design Patterns:
• adapter
• iterator
Summary
83 / 83