RW214: Data Structures and Algorithms L. van Zijl Department of Computer Science University of Stellenbosch CS214 – (1) RW214: Data Structures and Algorithms University of Stellenbosch Bags, Queues, Stacks Bags I Best implementation for efficiency? I Generics – parameterized types I Type parameters instantiated as reference types, Java maps to primitives I Autobox – automatically cast primitive type to wrapper type I Auto-unboxing – wrapper to primitive I Iterable collection (foreach) CS214 – (2) RW214: Data Structures and Algorithms University of Stellenbosch Bags, Queues, Stacks Bags I Duplicate items, order immaterial I Add items, iterate I Example – lots of numbers, average, std dev CS214 – (3) RW214: Data Structures and Algorithms University of Stellenbosch Bags, Queues, Stacks FIFO queue I FIFO service in order of arrival (queue at P&P) I Fairness – implementation must preserve relative order I Enqueue, dequeue I Example – read numbers from file, get size, dequeue into array CS214 – (4) RW214: Data Structures and Algorithms University of Stellenbosch Bags, Queues, Stacks (Pushdown) Stacks I LIFO service – items processed reverse order of arrival I Push, pop I Example: Arithmetic expression evaluator I How to convert a string to a value (parse, tokens, execute) I Two stack algorithm, page 129 CS214 – (5) RW214: Data Structures and Algorithms University of Stellenbosch Bags, Queues, Stacks Implementing collections I Fixed capacity stack of strings p 133 I Generalize with generics for any data type Item (p 135) I NOTE! No generic array creation in Java (cast) I Generalize capacity with array resizing (copy to new array) I Loitering – orphan I Iteration (pp 138-141): hasNext, next I LIFO stack p 141 model for items in array I NB! Operation time indep of collection size AND space used constant factor of coll. size I But resizing on push/pop time rel. to coll. size. Repair by using linked lists. RW214: Data Structures and Algorithms CS214 – (6) University of Stellenbosch Bags, Queues, Stacks Linked Lists I Recursive data structure of nodes (item+ref) I Operations: easy to insert/remove at beginning, insert at end I Traverse list to remove from end, remove/insert before/after given node I How to implement stack with linked list (p149) I How to implement queue with linked list (p151) [first, last ref] I NOTE! Space prop. to number items in coll., time indep. of size of coll. I See p155 for bags and iteration. CS214 – (7) RW214: Data Structures and Algorithms University of Stellenbosch