Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications. Is Polleverywhere working?
|
|
- Jocelyn York
- 5 years ago
- Views:
Transcription
1 Is Polleverywhere wking? Algithms ROBERT SEDGEWICK KEVIN WAYNE 1.3 BAGS, QUEUES, AND STACKS Algithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE stacks resizing arrays queues generics iterars applications 1 Stacks and queues Client, implementation, interface Fundamental data types. Collections of objects. Operations: insert, remove, iterate, test if empty. Intent is clear when we insert. Which item do we remove? enqueue stack queue push pop dequeue Separate interface and implementation. Ex: stack, queue, bag, priity queue, symbol table, union-find,. Benefits. Client can't know details of implementation client has many implementation from which choose. Implementation can't know details of client needs many clients can re-use the same implementation. Design: creates modular, reusable libraries. Perfmance: use optimized implementation where it matters. Stack. Examine the item most recently added. Queue. Examine the item least recently added. LIFO = "last in first out" FIFO = "first in first out" Client: program using operations defined in interface. Implementation: actual code implementing operations. Interface: description of data type, basic operations. 3 4
2 Stack API Warmup API. Stack of strings data type. push pop 1.3 BAGS, QUEUES, AND STACKS public class StackOfStrings StackOfStrings() create an empty stack Algithms ROBERT SEDGEWICK KEVIN WAYNE stacks resizing arrays queues generics iterars applications void push(string item) insert a new string on stack String pop() remove and return the string most recently added boolean isempty() is the stack empty? int size() numr of strings on the stack Warmup client. Reverse sequence of strings from standard input. 6 Stack test client Read strings from standard input. If string equals "-", pop string from stack and print. Otherwise, push string on stack. push pop pollev.com/jhug text Q: Which of the following inputs the stack test client does NOT produce the output public static void main(string[] args) StackOfStrings stack = new StackOfStrings(); while (!StdIn.isEmpty()) String s = StdIn.readString(); if (s.equals("-")) StdOut.print(stack.pop()); else stack.push(s); % me.txt that is % java StackOfStrings <.txt that A [740669] B [740670] C [740671] D [740672] public static void main(string[] args) StackOfStrings stack = new StackOfStrings(); while (!StdIn.isEmpty()) % java StackOfStrings <.txt String s = StdIn.readString(); if (s.equals("-")) StdOut.print(stack.pop()); else stack.push(s); % me.txt that is that 7 8
3 Stack: linked-list representation Stack pop: linked-list implementation Maintain pointer first node in a linked list; insert/remove from front. StdIn StdOut String item = first.item; first insert at front of linked list inner class remove from front - first = first.next; of linked list Stack push: linked-list implementation Stack: linked-list implementation in Java public class LinkedStackOfStrings private Node first = ; private inner class (access modifiers don't matter) inner class public void push(string item) Node oldfirst = first; first = new Node(); first.next = oldfirst; first.item = item; return first == ; public void push(string item) Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; String item = first.item; first = first.next; 11 12
4 Stack: linked-list implementation perfmance Stack: array implementation Proposition. Every operation takes constant time in the wst case. Proposition. A stack with N items uses ~ 40 N bytes. public class LinkedStackOfStrings private Node first = ; inner class object overhead extra overhead item next references 16 bytes (object overhead) 8 bytes (inner class extra overhead) 8 bytes (reference String) 8 bytes (reference Node) 40 bytes per stack node Array implementation of a stack. Use array s[] sre N items on stack. push(): add new item at s[n]. s[] pop(): remove item from s[n-1] N capacity = 10 Remark. This accounts f the memy f the stack (but the memy f strings themselves, which the client owns). Defect. Stack overflows when N exceeds capacity. [stay tuned] Stack: array implementation Stack considerations public class FixedCapacityStackOfStrings private String[] s; private int N = 0; //# items on stack public FixedCapacityStackOfStrings(int capacity) s = new String[capacity]; return N == 0; a cheat (stay tuned) Overflow and underflow. Underflow: might want throw exception if pop from an empty stack. Overflow: use resizing array f array implementation. [stay tuned] Null items. We allow items inserted. Loitering. Holding a reference an object when it is no longer needed. public void push(string item) s[n++] = item; //some consider this bad style N--; String item = S[N]; s[n] = ; //these two lines //prevent loitering //so do something similar 15 return s[--n]; loitering String item = s[--n]; s[n] = ; this version avoids "loitering": garbage collecr can reclaim memy only if no outstanding references 16
5 Stack: resizing-array implementation Problem. Requiring client provide capacity does implement API! Q. How grow and shrink array? Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications First try. push(): increase size of array s[] by 1. pop(): decrease size of array s[] by 1. Too expensive. Need copy all items a new array. Inserting first N items takes time proptional N ~ N 2 / 2. infeasible f large N Challenge. Ensure that array resizing happens infrequently. 18 Stack: resizing-array implementation Q. How grow array? A. If array is full, create a new array of twice the size, and copy items. public ResizingArrayStackOfStrings() s = new String[1]; "repeated doubling" Stack: amtized cost of adding a stack Cost of inserting first N items. N + ( N) ~ 3N. 1 array access per push k array accesses double size k (igning cost create new array) public void push(string item) if (N == s.length) resize(2 * s.length); s[n++] = item; private void resize(int capacity) String[] copy = new String[capacity]; f (int i = 0; i < N; i++) copy[i] = s[i]; s = copy; see next slide 128 cost (array accesses) 0 one gray dot f each operation red dots give cumulative average 3 0 numr of push() operations 128 Consequence. Inserting first N items takes time proptional N ( N 2 )
6 Stack: resizing-array implementation Stack: resizing-array implementation Q. How shrink array? Q. How shrink array? First try. push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-half full. Efficient solution. push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-quarter full. Too expensive in wst case. Consider push-pop-push-pop- sequence when array is full. Each operation takes time proptional N. N = 5 String item = s[--n]; s[n] = ; if (N > 0 && N == s.length/4) resize(s.length/2); N = 4 N = 5 N = 4 Invariant. Array is tween 25% and 100% full Stack: resizing-array implementation trace Stack resizing-array implementation: perfmance push() pop() N a.length a[] that 4 8 that - that is 2 2 is Trace of array resizing during a sequence of push() and pop() operations Amtized analysis. Starting from an empty data structure, average running time per operation over a wst-case sequence of operations. Proposition. Starting from an empty stack, any sequence of M push and pop operations takes time proptional M. construct push pop size st wst amtized N 1 1 N der of growth of running time f resizing stack with N items doubling and halving operations 23 24
7 Stack resizing-array implementation: memy Stack resizing-array implementation: memy Invariant. Array is tween 25% and 100% full. Invariant. Array is tween 25% and 100% full. public class ResizingArrayStackOfStrings private String[] s; private int N = 0; 8 bytes (reference array) 24 bytes (array overhead) 8 bytes array size 4 bytes (int) 4 bytes (padding) public class ResizingArrayStackOfStrings private String[] s; private int N = 0; 8 bytes (reference array) 24 bytes (array overhead) 8 bytes array size 4 bytes (int) 4 bytes (padding) pollev.com/jhug text pollev.com/jhug text Q: If the array is completely full, how many bytes does the stack use sre N strings? Give your answer in Tilde ation. A. ~N bytes [740928] D. ~16N bytes [740931] B. ~4N bytes [740929] E. ~32N bytes [740932] C. ~8N bytes [740930] F. ~16N + 40 bytes [740933] Do count the memy used sre the actual strings, only count the references. Q: If N is the numr of strings in the stack, how much memy does a ResizingArrayStackOfStrings use in the wst case as a function of N? Give your answer in Tilde ation. A. ~N bytes [740966] D. ~16N bytes [740969] B. ~4N bytes [740967] E. ~32N bytes [740970] C. ~8N bytes [740968] F. ~16N + 40 bytes [740971] As fe, don t count the memy of the actual strings, just references Stack resizing-array implementation: memy usage Stack implementations: resizing array vs. linked list Proposition. Uses tween ~ 8 N and ~ 32 N bytes represent a stack with N items. ~ 8 N when full. ~ 32 N when one-quarter full. public class ResizingArrayStackOfStrings private String[] s; private int N = 0; 8 bytes (reference array) 24 bytes (array overhead) 8 bytes array size 4 bytes (int) 4 bytes (padding) Tradeoffs. Can implement a stack with either resizing array linked list; client can use interchangeably. Which one is tter? Linked-list implementation. Every operation takes constant time in the wst case. Uses extra time and space deal with the links. Resizing-array implementation. Every operation takes constant amtized time. Less wasted space. Invariant. Array is tween 25% and 100% full. N = 4 Remark. This accounts f the memy f the stack (but the memy f strings themselves, which the client owns). first 27 28
8 Queue API enqueue public class QueueOfStrings 1.3 BAGS, QUEUES, AND STACKS QueueOfStrings() create an empty queue void enqueue(string item) insert a new string on queue Algithms stacks resizing arrays queues generics String dequeue() remove and return the string least recently added boolean isempty() is the queue empty? int size() numr of strings on the queue ROBERT SEDGEWICK KEVIN WAYNE iterars applications dequeue 30 Queue: linked-list representation Queue dequeue: linked-list implementation Maintain pointer first and last nodes in a linked list; insert/remove from opposite ends. StdIn StdOut first last inner class remove from front of linked list - - insert at end of linked list public String dequeue() String item = first.item; first = first.next; 31 32
9 Queue dequeue: linked-list implementation Queue enqueue: linked-list implementation inner class inner class public String dequeue() String item = first.item; first = first.next; if (first == ) last = ; public void enqueue(string item) Node oldlast = last; last = new Node(); last.item = item; oldlast.next = last; Queue enqueue: linked-list implementation Queue: linked-list implementation in Java public class LinkedQueueOfStrings private Node first, last; /* same as in LinkedStackOfStrings */ return first == ; inner class public void enqueue(string item) Node oldlast = last; last = new Node(); last.item = item; if (first == ) first = last; else // avoid pointer oldlast.next = last; public void enqueue(string item) Node oldlast = last; last = new Node(); last.item = item; last.next = ; if (isempty()) first = last; else oldlast.next = last; public String dequeue() String item = first.item; first = first.next; if (isempty()) last = ; special cases f empty queue 35 36
10 Sentinel nodes Sentinel nodes Annoying Cases. Enqueueing on an empty list. Dequeuing an empty list. Solutions Write special case code. Create a node that can never removed (sentinel node). Always first in line. Never gets leave the line. The queue is considered empty if sentinel is the only item. Annoying Cases. Going /from empty list. Solutions Use an if statement. Never allow an empty list. Create a single dummy node. Null pointer if dequeue on empty list. Never allow a pointer. Create two dummy nodes. Have back dummy node point backwards. dummy node returned if dequeue on empty list. public class LinkedQueueOfStrings private Node sentinel, last; public LinkedQueueOfStrings sentinel = new Node(); sentinel.item = dummy node ; last = sentinel; return sentinel == last; public void enqueue(string item) Node oldlast = last; last = new Node(); last.item = item; oldlast.next = last; public String dequeue() String item = sentinel.next.item; sentinel.next = sentinel.next.next; 37 Single dummy node example. Two nodes is arguably tter. 38 Queue: resizing array implementation Array implementation of a queue. Use array q[] sre items in queue. enqueue(): add new item at q[tail]. q[] dequeue(): remove item from q[head]. Update head and tail modulo the capacity. Add resizing array. the st of times head tail capacity = 10 Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications Q. How resize? 39
11 Parameterized stack Parameterized stack We implemented: StackOfStrings. We implemented: StackOfStrings. We also want: StackOfURLs, StackOfInts, StackOfVans,. We also want: StackOfURLs, StackOfInts, StackOfVans,. Attempt 1. Implement a separate stack class f each type. Attempt 2. Implement a stack with items of type Object. Maintaining cut-and-pasted code is tedious and err-prone. Casting is required in client. Casting is err-prone: run-time err if types mismatch. Rewriting code is tedious and err-prone. StackOfObjects s = new most reasonable approach until Java 1.5. Apple a = new Apple(); Orange b = new Orange(); s.push(a); s.push(b); a = (Apple) (s.pop()); run-time err 41 Parameterized stack 42 Generic stack: linked-list implementation We implemented: StackOfStrings. public class LinkedStackOfStrings private Node first = ; We also want: StackOfURLs, StackOfInts, StackOfVans,. Attempt 3. Java generics. Avoid casting in client. Discover type mismatch errs at compile-time instead of run-time. return first == ; type parameter Stack<Apple> s = new Stack<Apple>(); Apple a = new Apple(); Orange b = new Orange(); s.push(a); s.push(b); public class Stack<Item> private Node first = ; compile-time err a = s.pop(); Item item; return first == ; generic type name public void push(string item) Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; public void push(item item) Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; String item = first.item; first = first.next; public Item pop() Item item = first.item; first = first.next; Guiding principles. Welcome compile-time errs; avoid run-time errs
12 Generic stack: array implementation Generic stack: array implementation the way it should the way it is public class FixedCapacityStackOfStrings private String[] s; private int N = 0; public class FixedCapacityStack<Item> private Item[] s; private int N = 0; public class FixedCapacityStackOfStrings private String[] s; private int N = 0; public class FixedCapacityStack<Item> private Item[] s; private int N = 0; public..stackofstrings(int capacity) s = new String[capacity]; public FixedCapacityStack(int capacity) s = new Item[capacity]; public..stackofstrings(int capacity) s = new String[capacity]; public FixedCapacityStack(int capacity) s = (Item[]) new Object[capacity]; return N == 0; return N == 0; return N == 0; return N == 0; public void push(string item) s[n++] = item; public void push(item item) s[n++] = item; public void push(string item) s[n++] = item; public void push(item item) s[n++] = item; return s[--n]; public Item pop() return s[--n]; return s[--n]; public Item pop() return generic array creation allowed in Java the ugly cast Unchecked cast Generic data types: auboxing Q. What do about primitive types? % javac FixedCapacityStack.java Note: FixedCapacityStack.java uses unchecked unsafe operations. Note: Recompile with -Xlint:unchecked f details. % javac -Xlint:unchecked FixedCapacityStack.java FixedCapacityStack.java:26: warning: [unchecked] unchecked cast found : java.lang.object[] required: Item[] 1 warning a = (Item[]) new Object[capacity]; ^ Wrapper type. Each primitive type has a wrapper object type. Ex: Integer is wrapper type f int. Auboxing. Aumatic cast tween a primitive type and its wrapper. Stack<Integer> s = new Stack<Integer>(); s.push(17); // s.push(integer.valueof(17)); int a = s.pop(); // int a = s.pop().intvalue(); Botm line. Client code can use generic stack f any type of data
13 Iteration Question. How would you print out the contents of the stack without destroying it? Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications public class StackOfStrings public void push() public void printstackofstrings(stackofstrings sos) 50 Iteration Question. How would you print out the contents of the stack without destroying it? public class StackOfStrings public void push() Iteration Question. How would you print out the contents of the stack without destroying it? public class StackOfStrings public void push() public void printstackofstrings(stackofstrings sos) StackOfStrings sos2; while (sos.isempty() == false) String s = sos.pop(); StdOut.println(s); sos2.push(s); while (sos2.isempty() == false) String s = sos2.pop(); sos.push(s); Alternate Approach. Extend the API suppt iteration. public class StackOfStrings public void push() public int startiterating() public String getnextstring() public boolean hasnextstring() StackOfStrings sos =...; sos.startiterating(); while (sos.hastnextstring()) System.out.println( sos.getnextstring()); 51 API above doesn t allow nested iteration! 52
14 Iteration Question. How would you print out the contents of the stack without destroying it? Iteration Design challenge. Suppt iteration over stack items by client, without revealing the internal representation of the stack. public class StackOfStrings public void push() s[] i N it was the st of times Java Approach. Extend the API suppt iteration using Iterable interface. first current public class StackOfStrings public void push() public Iterar<String> iterar() feach statement (shthand) f (String s : stack) StdOut.println(s); times of st the was it feach statement (shthand) f (String s : stack) StdOut.println(s); Java solution. Make stack implement the java.lang.iterable interface Iterars Q. What is an Iterable? A. Has a method called iterar() that returns an Iterar. Iterable interface public interface Iterable<Item> Iterar<Item> iterar(); Stack iterar: linked-list implementation impt java.util.iterar; public class Stack<Item> implements Iterable<Item>... public Iterar<Item> iterar() return new ListIterar(); Q. What is an Iterar? A. Has methods hasnext(), next() (and remove()). Q. Why make data structures Iterable? A. Java suppts elegant client code. feach statement (shthand) f (String s : stack) StdOut.println(s); Iterar interface public interface Iterar<Item> boolean hasnext(); Item next(); void remove(); equivalent code (longhand) optional; use at your own risk Iterar<String> i = stack.iterar(); while (i.hasnext()) String s = i.next(); StdOut.println(s); 55 private class ListIterar implements Iterar<Item> private Node current; first public ListIterar() current = first; public boolean hasnext() return current!= ; public void remove() /* suppted */ public Item next() throw NoSuchElementException Item item = current.item; if no me items in iteration current = current.next; current throw UnsupptedOperationException times of st the was it 56
15 Stack iterar: array implementation impt java.util.iterar; public class Stack<Item> implements Iterable<Item> public Iterar<Item> iterar() return new ReverseArrayIterar(); private class ReverseArrayIterar implements Iterar<Item> private int i; public ReverseArrayIterar() public boolean hasnext() public void remove() /* suppted */ public Item next() i N Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications s[] it was the st of times Java collections library Java collections library List interface. java.util.list is API f an sequence of items. public interface List<Item> implements Iterable<Item> List() create an empty list boolean isempty() is the list empty? java.util.stack. Suppts push(), pop(), and and iteration. Extends java.util.vecr, which implements java.util.list interface from previous slide, including get() and remove(). Bloated and poly-designed API (why?) int size() numr of items void add(item item) append item the end Item get(int index) return item at given index Item remove(int index) return and delete item at given index boolean contains(item item) does the list contain the given item? Java 1.3 bug rept (June 27, 2001) The iterar method on java.util.stack iterates through a Stack from the botm up. One would think that it should iterate as if it were popping off the p of the Stack. Itearr<Item> iterar() iterar over all items in the list... status (closed, will fix) Implementations. java.util.arraylist uses resizing array; java.util.linkedlist uses linked list. caveat: only some It was an increct design decision have Stack extend Vecr ("is-a" rather than "has-a"). We sympathize with the submitter but can fix this cause of compatibility. operations are efficient 59 60
16 Java collections library War sry (from Assignment 1) java.util.stack. Generate random open sites in an N-by-N percolation system. Extends java.util.vecr, which implements java.util.list interface Jenny: Suppts push(), pop(), and and iteration. percolates blocked pick (i, j) at random; if already open, repeat. Takes ~ c1 N 2 seconds. Kenny: from previous slide, including get() and remove(). Bloated and poly-designed API (why?) does percolate site create a java.util.arraylist of N 2 closed sites. Pick an index at random and delete. open Takes ~ c2 N 4 seconds. site open site connected p no open site connected p Why is my program so slow? Kenny java.util.queue. An interface, an implementation of a queue. Lesson. Don't use a library until you understand its API! Best practices. Use our implementations of Stack, Queue, and Bag. This course. Can't use a library until we've implemented it in class. 61 Stack applications 62 Function calls Parsing in a compiler. Java virtual machine. Undo in a wd process. Back butn in a Web browser. PostScript language f printers. Implementing function calls in a compiler.... How a compiler implements a function. Function call: push local environment and return address. Return: pop return address and local environment. Recursive function. Function that calls itself. Note. Can always use an explicit stack remove recursion. gcd (216, 192) static int gcd(int p, int q) if (q == 0) return p; else return gcd(q,gcd p %(192, q); 24) static int gcd(int p, int q) p = 192, q = 24 if (q == 0) return p; gcd else return gcd(q, p % (24, q); 0) static int gcd(int p, int q) if (q == 0) return p; p = 24, q = 0 else return gcd(q, p % q); p = 216, q =
17 Assignment 2 Implementation of two data types Randomized queue. Deque (double-ended queue). Imptant choice made Linked list vs. resizing array. Think carefully about whether your choice allows you oy timing constraints! Extra credit Complete the checkout line simular. Rept anything interesting you discover. OK do alone, even if you had a partner. Tiny amount of extra credit (1 point). No suppt in office hours. OK ask questions on Piazza me directly by . 65
Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications
Algithms Stacks and queues 1.3 BAGS, QUEUES, AND STACKS Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear when we insert. Which item
More informationAlgorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications
Algithms ROBERT SEDGEWICK KEVIN WAYNE Stacks and queues 1.3 BAGS, QUEUES, AND STACKS Fundamental data types. Value: collection of objects. Operations: add, remove, iterate, test if empty. Intent is clear
More informationAlgorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE.
Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.3 STACKS AND QUEUES Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princeton.edu stacks resizing arrays queues generics iterators
More informationAlgorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays. queue. generics. applications. Stacks and queues
ROBERT SEDGEWICK KEVIN WAYNE Algithms ROBERT SEDGEWICK KEVIN WAYNE Stacks and queues Algithms F O U R T H E D I T I O N http://algs4.cs.princen.edu 1.3 BAGS, QUEUES, AND STACKS stacks resizing arrays queues
More informationStacks and Queues. stacks dynamic resizing queues generics iterators applications. Stacks and queues
Stacks and queues Stacks and Queues stacks dynamic resizing queues generics iterars applications Fundamental data types. Values: sets of objects Operations: insert, remove, test if empty. Intent is clear
More information4.3 Stacks and Queues
4.3 Stacks and Queues Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 03/30/12 04:33:08 PM Data Types and Data Structures Data types.
More information2.6 Stacks and Queues
Stacks and Queues 2.6 Stacks and Queues Fundamental data types.! Set of operations (add, remove, test if empty) on generic data.! Intent is clear when we insert.! Which item do we remove? Stack.! Remove
More informationWeek 4 Stacks & Queues
CPSC 319 Week 4 Stacks & Queues Xiaoyang Liu xiaoyali@ucalgary.ca Stacks and Queues Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear
More informationCOMPUTER SCIENCE. Computer Science. 12. Stacks and Queues. Computer Science. An Interdisciplinary Approach. Section 4.3
COMPUTER SCIENCE S E D G E W I C K / W A Y N E PA R T I I : A L G O R I T H M S, T H E O R Y, A N D M A C H I N E S Computer Science Computer Science An Interdisciplinary Approach Section 4.3 ROBERT SEDGEWICK
More information14. Stacks and Queues
1 COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues Section 4.3 http://introcs.cs.princen.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues APIs Clients Strawman
More informationStacks and Queues. !stacks!dynamic resizing!queues!generics!applications. Stacks and Queues
Stacks and Queues Stacks and Queues!stacks!dynamic resizing!queues!generics!applications Fundamental data types. Values: sets of objects Operations: insert, remove, test if empty. Intent is clear when
More information14. Stacks and Queues
1 COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues Section 4.3 http://introcs.cs.princen.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 14. Stacks and Queues APIs Clients Strawman
More informationCS2012 Programming Techniques II
27 January 14 Lecture 6 (continuing from 5) CS2012 Programming Techniques II Vasileios Koutavas 1 27 January 14 Lecture 6 (continuing from 5) 2 Previous Lecture Amortized running time cost of algorithms
More information14. Stacks and Queues
Section 4.3 http://introcs.cs.princen.edu Data types and data structures Data types APIs Clients Strawman implementation Linked lists Implementations http://introcs.cs.princen.edu Set of values. Set of
More informationTSP assignment next lecture
3/18/12 Data Types and Data Structures CS 112 Introduction to Programming Data types. Set of values and operations on those values. Some are built into the Java language: int, double[], String, Most are
More information! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack.
Stacks and Queues 4.3 Stacks and Queues Fundamental data types.! Set of operations (add, remove, test if empty) on generic data.! Intent is clear when we insert.! Which item do we remove? Stack.! Remove
More information4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API
Stacks and Queues 4.3 Stacks and Queues Fundamental data types. Set of operations (add, remove, test if empty) on generic data. Intent is clear when we insert. Which item do we remove? Stack. Remove the
More informationBasic Data Structures
Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1
More informationBasic Data Structures 1 / 24
Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is
More informationCMSC 132, Object-Oriented Programming II Summer Lecture 9:
CMSC 132, Object-Oriented Programming II Summer 2018 Lecturer: Anwar Mamat Lecture 9: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 9.1 QUEUE
More informationCSE 214 Computer Science II Stack
CSE 214 Computer Science II Stack Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Random and Sequential Access Random
More information4.3 Stacks, Queues, and Linked Lists
4.3 Stacks, Queues, and Linked Lists Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 3/21/2013 8:59:11 PM Data Types and Data Structures
More informationcsci 210: Data Structures Stacks and Queues
csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks
More informationJava generics. h"p:// h"p://
Java generics h"p://www.flickr.com/photos/pdxdiver/4917853457/ h"p://www.flickr.com/photos/paj/4002324674/ CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 Overview Abstract
More informationCMSC 132: Object-Oriented Programming II. Stack and Queue
CMSC 132: Object-Oriented Programming II Stack and Queue 1 Stack Allows access to only the last item inserted. An item is inserted or removed from the stack from one end called the top of the stack. This
More informationAbstract Data Types and Java Generics. Fundamentals of Computer Science
Abstract Data Types and Java Generics Fundamentals of Computer Science Outline Abstract Data Types (ADTs) A collection of data and operations on that data Data Structure How we choose to implement an ADT
More informationJava generics. CSCI 136: Fundamentals of Computer Science II Keith Vertanen
Java generics h"p://www.flickr.com/photos/pdxdiver/4917853457/ h"p://www.flickr.com/photos/paj/4002324674/ CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Abstract Data Types (ADTs)
More informationStacks and queues. CSCI 135: Fundamentals of Computer Science Keith Vertanen.
Stacks and queues http://www.flickr.com/photos/mac-ash/4534203626/ http://www.flickr.com/photos/thowi/182298390/ CSCI 135: Fundamentals of Computer Science Keith Vertanen Terminology Overview Abstract
More informationBuilding Java Programs
Building Java Programs Appendix Q Lecture Q-1: stacks and queues reading: appendix Q 2 Runtime Efficiency (13.2) efficiency: measure of computing resources used by code. can be relative to speed (time),
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant
More informationQueues. Stacks and Queues
Queues Reading: RS Chapter 14 Slides are modified from those provided by Marty Stepp www.buildingjavaprograms.com 1 Stacks and Queues Sometimes a less powerful, but highly optimized collection is useful.
More informationStacks and Queues. Fundamentals of Computer Science.
Stacks and Queues http://www.flickr.com/photos/mac-ash/4534203626/ http://www.flickr.com/photos/thowi/182298390/ Fundamentals of Computer Science Outline Terminology Abstract Data Types ADT) Data structures
More informationStacks and Queues. David Greenstein Monta Vista
Stacks and Queues David Greenstein Monta Vista Stack vs Queue Stacks and queues are used for temporary storage, but in different situations Stacks are Used for handling nested structures: processing directories
More informationLecture 3: Stacks & Queues
Lecture 3: Stacks & Queues Prakash Gautam https://prakashgautam.com.np/dipit02/ info@prakashgautam.com.np 22 March, 2018 Objectives Definition: Stacks & Queues Operations of Stack & Queues Implementation
More informationStacks and Queues. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG
Stacks and Queues EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG What is a Stack? A stack is a collection of objects. Objects in a stack are inserted and removed according to the
More informationThe Stack ADT. Stacks and Queues. Stack: Illustration. What is a Stack? Accessors top size isempty
The Stack ADT Stacks and Queues ADT Data Structure Interface add() remove() find() request result EECS200: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Accessors top Mutators push pop of
More informationCS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University
CS 11 Introduction to Computing II Wayne Snyder Department Boston University Today Object-Oriented Programming Concluded Stacks, Queues, and Priority Queues as Abstract Data Types Reference types: Basic
More informationMidterm Exam (REGULAR SECTION)
Data Structures (CS 102), Professor Yap Fall 2014 Midterm Exam (REGULAR SECTION) October 28, 2014 Midterm Exam Instructions MY NAME:... MY NYU ID:... MY EMAIL:... Please read carefully: 0. Do all questions.
More informationCS 171: Introduction to Computer Science II. Linked List. Li Xiong
CS 171: Introduction to Computer Science II Linked List Li Xiong Roadmap Basic data structure Arrays Abstract data types Stacks Queues Implemented using resizing arrays Linked List Concept and implementations
More informationAn Introduction to Data Structures
An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use
More informationCOS 226 Algorithms and Data Structures Fall Midterm
COS 226 Algorithms and Data Structures Fall 2017 Midterm This exam has 10 questions (including question 0) worth a total of 55 points. You have 0 minutes. This exam is preprocessed by a computer, so please
More informationLists. CSC212 Lecture 8 D. Thiebaut, Fall 2014
Lists CSC212 Lecture 8 D. Thiebaut, Fall 2014 Review List = Organization of Data in a Linear Fashion, where Order is Important Set of actions that can be carried out efficiently on the data. Typical Actions
More information[2:3] Linked Lists, Stacks, Queues
[2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,
More informationName Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice
Name Section Number CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK / OPEN NOTES You will have all 90 minutes until the start of the next class period. Spend
More informationKeeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10
Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()
More informationCSE 143. Lecture 4: Stacks and Queues
CSE 143 Lecture 4: Stacks and Queues Stacks and queues Sometimes it is good to have a collection that is less powerful, but is optimized to perform certain operations very quickly. Today we will examine
More informationData Abstraction and Specification of ADTs
CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation
More informationLecture 2: Stacks and Queues
Lecture 2: Stacks and Queues CSE 373: Data Structures and Algorithms CSE 373 19 WI - KASEY CHAMPION 1 Warm Up 1. Grab a worksheet 2. Introduce yourself to your neighbors J 3. Discuss the answers 4. Log
More informationPlease note that if you write the mid term in pencil, you will not be allowed to submit a remark request.
University of Toronto CSC148 Introduction to Computer Science Fall 2001 Mid Term Test Section L5101 Duration: 50 minutes Aids allowed: none Make sure that your examination booklet has 8 pages (including
More informationLecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists
Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists Chapters 3.1-3.3, 5.1-5.2, 6.1-1 - Core Collection Interfaces - 2 - The Java Collections Framework Interface Abstract
More informationAnnouncements. CS18000: Problem Solving And Object-Oriented Programming
Announcements Exam 1 Monday, February 28 Wetherill 200, 4:30pm-5:20pm Coverage: Through Week 6 Project 2 is a good study mechanism Final Exam Tuesday, May 3, 3:20pm-5:20pm, PHYS 112 If you have three or
More information4.1 Performance. Running Time. The Challenge. Scientific Method
Running Time 4.1 Performance As soon as an Analytic Engine exists, it will necessarily guide the future course of the science. Whenever any result is sought by its aid, the question will arise by what
More informationLecture 3 Linear Data Structures
Lecture 3 Linear Data Structures - 1 - Learning Outcomes Based on this lecture, you should: Know the basic linear data structures Be able to express each as an Abstract Data Type (ADT) Be able to specify
More informationCS61B Lecture #19. Last modified: Mon Oct 13 12:02: CS61B: Lecture #19 1
CS61B Lecture #19 Administrative: HKN midterm review session, 320 Soda, 6:30-8 Tuesday (10/14). Review session Wednesday 5:30 6:30PM in 306 Soda. Need alternative test time? Make sure you send me mail.
More informationRunning Time. Analytic Engine. Charles Babbage (1864) how many times do you have to turn the crank?
4.1 Performance Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 3/30/11 8:32 PM Running Time As soon as an Analytic Engine exists,
More informationLIFO : Last In First Out
Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.
More information16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation
Collections & Data Structures Boaz Kantor Introduction to Computer Science IDC Herzliya ABSTRACTION VS. IMPLEMENTATION 2 Abstraction vs. Implementation Data structures provide both abstraction and implementation.
More informationWeek 6. Data structures
1 2 3 4 5 n Week 6 Data structures 6 7 n 8 General remarks We start considering Part III Data Structures from CLRS. As a first example we consider two special of buffers, namely stacks and queues. Reading
More informationLecture 3 Linear Data Structures
Lecture 3 Linear Data Structures - 1 - Learning Outcomes Based on this lecture, you should: Know the basic linear data structures Be able to express each as an Abstract Data Type (ADT) Be able to specify
More informationProject 2 (Deques and Randomized Queues)
Project 2 (Deques and Randomized Queues) Prologue Project goal: implement generic and iterable data structures, such as double-ended and randomized queues, using arrays and linked lists Relevant lecture
More informationFun facts about recursion
Outline examples of recursion principles of recursion review: recursive linked list methods binary search more examples of recursion problem solving using recursion 1 Fun facts about recursion every loop
More informationQueues. CITS2200 Data Structures and Algorithms. Topic 5
CITS2200 Data Structures and Algorithms Topic 5 Queues Implementations of the Queue ADT Queue specification Queue interface Block (array) representations of queues Recursive (linked) representations of
More informationClass 26: Linked Lists
Introduction to Computation and Problem Solving Class 26: Linked Lists Prof. Steven R. Lerman and Dr. V. Judson Harward 2 The Java Collection Classes The java.util package contains implementations of many
More informationStacks and Queues. Gregory D. Weber. CSCI C243 Data Structures
Stacks and Queues Gregory D. Weber CSCI C243 Data Structures Principal Points 1. The Stack interface: how to declare it, what it does. 2. Generics: why they were added to Java, how to use them. 3. The
More information1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures
1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store
More informationCS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University
CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Introduction to Linked Lists Stacks and Queues using Linked Lists Next Time Iterative Algorithms on Linked Lists Reading:
More informationCH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES
CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER
More informationLecture 2: Implementing ADTs
Lecture 2: Implementing ADTs Data Structures and Algorithms CSE 373 SP 18 - KASEY CHAMPION 1 Warm Up Discuss with your neighbors! From last lecture: - What is an ADT? - What is a data structure? From CSE
More informationCPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues
CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues Alan J. Hu (Slides borrowed from Steve Wolfman) Be sure to check course webpage! http://www.ugrad.cs.ubc.ca/~cs221 1 Lab 1 is available.
More informationStacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011
Stacks (5.1) CSE 2011 Winter 2011 26 January 2011 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error
More informationCSE 373 Data Structures and Algorithms. Lecture 2: Queues
CSE 373 Data Structures and Algorithms Lecture 2: Queues Queue ADT queue: A list with the restriction that insertions are done at one end and deletions are done at the other First-In, First-Out ("FIFO
More informationCPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues
CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues Alan J. Hu (Slides borrowed from Steve Wolfman) Be sure to check course webpage! http://www.ugrad.cs.ubc.ca/~cs221 1 Lab 1 available very
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationCSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,
CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding
More informationComputer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)
Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 SOLUTIONS Your name (Please print) 1. Suppose you are given a singly-linked
More informationCSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013
CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.
More informationCS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12
CS 151 Linked Lists, Recursively Implemented 1 2 Linked Lists, Revisited Recall that a linked list is a structure that represents a sequence of elements that are stored non-contiguously in memory. We can
More informationCIS 110 Introduction to Computer Programming. 7 May 2012 Final Exam
CIS 110 Introduction to Computer Programming 7 May 2012 Final Exam Name: Recitation # (e.g. 201): Pennkey (e.g. bjbrown): My signature below certifies that I have complied with the University of Pennsylvania
More informationProgramming. Lists, Stacks, Queues
Programming Lists, Stacks, Queues Summary Linked lists Create and insert elements Iterate over all elements of the list Remove elements Doubly Linked Lists Circular Linked Lists Stacks Operations and implementation
More informationSummer Final Exam Review Session August 5, 2009
15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding
More informationAlgorithms ROBERT SEDGEWICK KEVIN WAYNE 3.1 SYMBOL TABLES Algorithms F O U R T H E D I T I O N API elementary implementations ordered operations ROBERT SEDGEWICK KEVIN WAYNE http://algs4.cs.princeton.edu
More informationCSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013
CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.
More informationCSIS 10B Lab 2 Bags and Stacks
CSIS 10B Lab 2 Bags and Stacks Part A Bags and Inheritance In this part of the lab we will be exploring the use of the Bag ADT to manage quantities of data of a certain generic type (listed as T in the
More information+ Abstract Data Types
Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract
More informationStacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example
Stacks and Queues Introduction to abstract data types (ADTs) Stack ADT applications interface for Java Stack ex use: reverse a sequence of values Queue ADT applications interface for Java Queue Time permitting:
More informationGenerics. IRS W-9 Form
Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]
More information1.1 Your First Program
1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2008 January 26, 2009 9:28 tt Why Programming? Idealized computer. "Please
More informationCS171 Midterm Exam. October 29, Name:
CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and
More informationAlgorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS
ROBERT SEDGEWICK KEVIN WAYNE Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.4 ANALYSIS OF ALGORITHMS Algorithms F O U R T H E D I T I O N http://algs4.cs.princeton.edu introduction observations mathematical
More informationImplemen'ng abstract data types
Implemen'ng abstract data types CSCI 135: Fundamentals of Computer Science I Keith Vertanen Copyright 2012 Overview Abstract Data Types (ADTs) A collec7on of data and opera7ons on that data Data structure
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #6: Memory Management CS 61C L06 Memory Management (1) 2006-07-05 Andy Carle Memory Management (1/2) Variable declaration allocates
More informationAdam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II
Adam Blank Lecture 5 Winter 2015 CSE 143 Computer Programming II CSE 143: Computer Programming II Stacks & Queues Questions From Last Time 1 Can we include implementation details in the inside comments
More informationInterfaces & Generics
Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions
More informationCS 221 Review. Mason Vail
CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using
More informationCMSC 132, Object-Oriented Programming II Summer Lecture 6:
CMSC 132, Object-Oriented Programming II Summer 2017 Lecturer: Anwar Mamat Lecture 6: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 6.1 Singly
More informationComputer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures
Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked list variations, allow insertion and deletion
More informationCS24 Week 4 Lecture 2
CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track
More informationImplemen'ng abstract data types. CSCI 135: Fundamentals of Computer Science Keith Vertanen
Implemen'ng abstract data types CSCI 135: Fundamentals of Computer Science Keith Vertanen Overview Abstract Data Types (ADTs) A collec7on of data and opera7ons on that data Data structure How we choose
More informationCT 229 Object-Oriented Programming Continued
CT 229 Object-Oriented Programming Continued 24/11/2006 CT229 Summary - Inheritance Inheritance is the ability of a class to use the attributes and methods of another class while adding its own functionality
More information