Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays. queue. generics. applications. Stacks and queues

Size: px
Start display at page:

Download "Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays. queue. generics. applications. Stacks and queues"

Transcription

1 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 BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars see precept applications Abstract data types. Value: collection of objects. Operations: add, remove, iterate, test if empty. Intent is clear when we add. Which item do we remove? enqueue stack queue Stack. Examine the item. Queue. Examine the item. push pop dequeue LIFO = "last in out" FIFO = " in out" Last updated on 2/8/16 7:22 AM 2 Client, implementation, API Interfaces can ambiguous Separate client and implementation via API. An Abstract Data type is one type of API. Benefits. Design: creates modular, reusable libraries. Perfmance: substitute optimized implementation when it matters. Client API Implementation API: description of data type, basic operations. Client: program using operations defined in API. Implementation: actual code implementing operations. Ex. Stack, queue, bag, priity queue, symbol table, union-find,. 3 Stacks and queues. Value: collection of objects. Operations: add, remove, iterate, test if empty. Q. What are two ways in which the semantics of iteration can ambiguous? A. What der iterate in: same as removal der does client not care? What happens if collection is modified during iteration? 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. status (closed, will not fix) It was an increct design decision have Stack extend Vecr ("is-a" rather than "has-a"). We sympathize with the submitter but cannot fix this cause of compatibility. 4

2 Ambiguity in the semantics of interfaces leads bugs Layers in a computer system Example: Mars climate biter. Lost due metric vs. imperial mishap in contract tween NASA & Lockheed Program API Libraries This lecture Programming language Operating system Hardware 5 6 Stack API Warmup API. Stack of strings data type. push pop public class StackOfStrings 1.3 BAGS, QUEUES, stacks resizing arrays Algithms R OBERT S EDGEWICK K EVIN W AYNE queues generics AND S TACKS StackOfStrings() void push(string item) String pop() boolean isempty() int size() create an empty stack add a new string stack remove and return the string is the stack empty? numr of strings on the stack iterars applications 8

3 Stacks quiz 1 How implement a stack with a singly-linked list? A. Stack: linked-list implementation Maintain pointer node in a singly-linked list. Push new item fe. Pop item from. it was the st of B. of st the was it C. None of the above. of st the was it D. I don't know Stack pop: linked-list implementation Stack push: linked-list implementation save item return String item =.item; delete node save a link the list Node old = ; old inner class String item; Node next; =.next; inner class String item; Node next; create a new node f the ginning = new Node(); old set the instance variables in the new node return saved item return item;.item = "not";.next = old; not 11 12

4 Stack: linked-list implementation in Java Stack: linked-list implementation perfmance public class LinkedStackOfStrings private Node = ; private String item; private Node next; public boolean isempty() return == ; public void push(string item) Node old = ; = new Node();.item = item;.next = old; public String pop() String item =.item; =.next; return item; private inner class (access modifiers f instance variables don't matter) Proposition. Every operation takes constant time in the wst case. Proposition. A stack with n items uses ~ 40 n bytes. inner class String item; Node next; object overhead extra overhead item next references Remark. This accounts f the memy f the stack 16 bytes (object overhead) 8 bytes (inner class extra overhead) 8 bytes (reference String) 8 bytes (reference Node) 40 bytes allocated per stack node (but not memy f the strings themselves, which the client owns) Stacks quiz 2 How implement a fixed-capacity stack with an array? A. B. it was the st of times times of st the was it B. None of the above. C. I don't know. Fixed-capacity stack: array implementation Use array s[] sre n items on stack. push(): add new item at s[n]. pop(): remove item from s[n-1]. s[] it was the st of times n capacity = 10 Defect. Stack overflows when n exceeds capacity. [stay tuned] 15 16

5 Fixed-capacity stack: array implementation Stack considerations public class FixedCapacityStackOfStrings private String[] s; private int n = 0; public FixedCapacityStackOfStrings(int capacity) s = new String[capacity]; public boolean isempty() return n == 0; a cheat (stay tuned) Overflow and underflow. Underflow: throw exception if pop from an empty stack. Overflow: use "resizing array" f array implementation. [stay tuned] Null items. We allow items added. Duplicate items. We allow an item added me than once. Loitering. Holding a reference an object when it is no longer needed. use index in array; then increment n public void push(string item) s[n++] = item; public String pop() return s[--n]; public String pop() return s[--n]; loitering public String pop() String item = s[--n]; s[n] = ; return item; decrement n; then use index in array this version avoids "loitering": garbage collecr can reclaim memy f an object only if no remaining references Stack: resizing-array implementation Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications Problem. Requiring client provide capacity does not implement API! Q. How grow and shrink array? 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, f each operation. Array accesses add n items = n + ( (n 1)) ~ n2. 1 array access per push Challenge. Ensure that array resizing happens infrequently. infeasible f large n 2(k 1) array accesses expand size k (igning cost create new array) 20

6 Why isn t array resizing easier? Stack: resizing-array implementation Q. Why no way increment array size except by creating new one? A. Because Java doesn t let us Because OS doesn t let us safely write past memy bounds Because memy is fragmented at the hardware level 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" Program Library Programming language Operating system See Applications section Data structures (ArrayStack) Basic data types (Array) Memy allocation API / Abstract Data Type / Interface (Stack)* Memy fragmentation 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; Hardware Physical memy *Note: in this course Stack is a class and not an interface 21 Array accesses add n = 2 i items. n + ( n) ~ 3n. 1 array access per push k array accesses double size k (igning cost create new array) 22 Stack: resizing-array implementation Stack: resizing-array implementation Q. How shrink array? First try. Q. How shrink array? Efficient solution. push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-half full. Too expensive in wst case. Consider push-pop-push-pop- sequence when array is full. Each operation takes time proptional n. full not push(): double size of array s[] when array is full. pop(): halve size of array s[] when array is one-quarter full. public String pop() String item = s[--n]; s[n] = ; if (n > 0 && n == s.length/4) resize(s.length/2); return item; push("") not pop() not push("") not Invariant. Array is tween 25% and 100% full

7 Stack resizing-array implementation: perfmance Stack resizing-array implementation: perfmance 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. typical wst amtized construct push 1 n 1 pop 1 n 1 size der of growth of running time f resizing array stack with n items doubling and halving 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. Proof. Divide the operations in batches. Each batch starts after a resize has just completed ( at the ginning) and ends with the next resize ( at the end). Claim: the cost of processing each batch is proptional the numr of operations in that batch. Exercise: complete this argument. Exercise: would proof hold if we d had different constants instead of ½ and ¼ (say ⅔ & ⅓)? What are the facrs consider in picking the constants? Stack resizing-array implementation: memy usage Proposition. A ResizingArrayStackOfStrings uses ~ 8n ~ 32n bytes of memy f a stack with n items. ~ 8n when full. ~ 32n when one-quarter full. public class ResizingArrayStackOfStrings private String[] s; private int n = 0; 8 bytes array size Remark. This accounts f the memy f the stack (but not the memy f strings themselves, which the client owns). Stack implementations: resizing array vs. linked list 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. n = 4 not not 27 28

8 Queue API enqueue public class QueueOfStrings Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications QueueOfStrings() create an empty queue void enqueue(string item) add a new string queue String dequeue() remove and return the string boolean isempty() is the queue empty? int size() numr of strings on the queue dequeue 30 Queues quiz 1 Queue: linked-list implementation How implement a queue with a singly-linked linked list? A. times of st the was it Maintain one pointer node in a singly-linked list. Maintain another pointer last last node. Dequeue from. Enqueue after last. B. it was the st of times it was the st of times C. None of the above. last D. I don't know

9 Queue dequeue: linked-list implementation Queue enqueue: linked-list implementation save a link the last node save item return Node oldlast = last; String item =.item; oldlast last delete node inner class String item; Node next; =.next; last last inner class String item; Node next; create a new node f the end last = new Node(); last.item = "not"; oldlast last not link the new node the end of the list return saved item return item; oldlast.next = last; oldlast last not Remark. Identical code linked-list stack pop() Queue: linked-list implementation in Java Queues quiz 2 public class LinkedQueueOfStrings private Node, last; /* same as in LinkedStackOfStrings */ public boolean isempty() return == ; public void enqueue(string item) Node oldlast = last; last = new Node(); last.item = item; last.next = ; if (isempty()) = last; else oldlast.next = last; special cases f empty queue How implement a fixed-capacity queue with an array? A. B. it was the st of times times of st the was it public String dequeue() String item =.item; =.next; if (isempty()) last = ; return item; C. None of the above. D. I don't know

10 Queue: resizing-array implementation Queue with two stacks Use array q[] sre items in queue. Job interview problem. Implement a queue with two stacks so that: enqueue(): dequeue(): Each queue op uses a constant amtized numr of stack ops. At most constant extra memy (sides the two stacks). add new item at q[tail]. remove item from q[head]. Update head and tail modulo the capacity. Add resizing array. Solution. Call the two stacks incoming and outgoing. enqueue: push incoming dequeue: pop from outgoing if outgoing is empty, pour incoming in outgoing (O(N)). isempty: check if both stacks are empty q[] 0 1 the st of times head tail Analysis: crectness. Left as exercise. capacity = 10 Analysis: efficiency. Consider the lifecycle of each item: pushed in incoming, popped from incoming, pushed in outgoing, popped from outgoing. Q. How resize? At most 4 stack operations per item. [Exercise: complete this argument.] Parameterized stack We implemented: StackOfStrings. We also want: StackOfURLs, StackOfInts, StackOfApples, StackOfOranges,. Solution in Java: generics. 1.3 BAGS, QUEUES, stacks resizing arrays Algithms R OBERT S EDGEWICK K EVIN W AYNE queues generics iterars applications AND S TACKS type parameter (use both specify type and call construcr) Stack<Apple> stack = new Stack<Apple>(); Apple apple = new Apple(); Orange ange = new Orange(); stack.push(apple); stack.push(ange); compile-time err... Guiding principle. Welcome compile-time errs; avoid run-time errs. 40

11 Generic stack: linked-list implementation Generic stack: array implementation public class LinkedStackOfStrings private Node = ; String item; Node next; public boolean isempty() return == ; public void push(string item) Node old = ; = new Node();.item = item;.next = old; public String pop() String item =.item; =.next; return item; public class LinkedStack<Item> private Node = ; Item item; Node next; public boolean isempty() return == ; public void push(item item) Node old = ; = new Node();.item = item;.next = old; public Item pop() Item item =.item; =.next; return item; generic type name public class FixedCapacityStackOfStrings private String[] s; private int n = 0; public..stackofstrings(int capacity) s = new String[capacity]; public boolean isempty() return n == 0; public void push(string item) s[n++] = item; public String pop() return s[--n]; the way it should public class FixedCapacityStack<Item> private Item[] s; private int n = 0; public FixedCapacityStack(int capacity) s = new Item[capacity]; public boolean isempty() return n == 0; public void push(item item) s[n++] = item; public Item pop() return s[--n]; generic array creation not allowed in Java Generic stack: array implementation Generic data types: auboxing and unboxing the way it is Q. What do about primitive types? public class FixedCapacityStackOfStrings private String[] s; private int n = 0; public..stackofstrings(int capacity) s = new String[capacity]; public class FixedCapacityStack<Item> private Item[] s; private int n = 0; public FixedCapacityStack(int capacity) s = (Item[]) new Object[capacity]; Wrapper type. Each primitive type has a wrapper object type. Ex: Integer is wrapper type f int. public boolean isempty() return n == 0; public boolean isempty() return n == 0; Auboxing. Aumatic cast from primitive type wrapper type. public void push(string item) s[n++] = item; public void push(item item) s[n++] = item; Unboxing. Aumatic cast from wrapper type primitive type. public String pop() return s[--n]; public Item pop() return s[--n]; Stack<Integer> stack = new Stack<Integer>(); stack.push(17); // stack.push(integer.valueof(17)); int a = stack.pop(); // int a = stack.pop().intvalue(); ugly cast (will result in a compile-time warning, but it s not your fault) 43 Botm line. Client code can use generic stack f any type of data. 44

12 Iteration Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications see precept Design challenge. Suppt iteration over stack items by client, without revealing the internal representation of the stack. resizing-array representation s[] linked-list representation it was the st of current times of st the was it Java solution. Use a f-each loop. i time s n F-each loop Iterars Java provides elegant syntax f iteration over collections. F a user-defined collection, do this enable looping over it with f-each: Data type must have a method named iterar(). The iterar() method returns an object that has two ce methods. f-each loop (shthand) Stack<String> stack;... f (String s : stack)... equivalent code (longhand) Stack<String> stack;... Iterar<String> i = stack.iterar(); while (i.hasnext()) String s = i.next(); the hasnext() methods returns false when there are no me items the next() method returns the next item in the collection To suppt f-each loops, Java provides two interfaces. Iterar interface: next() and hasnext() methods. Iterable interface: iterar() method that returns an Iterar. Both should used with generics. java.util.iterar interface public interface Iterar<Item> boolean hasnext(); Item next(); void remove(); Type safety. optional; use at your own risk java.lang.iterable interface public interface Iterable<Item> Iterar<Item> iterar(); iterar(); Data type must use these interfaces suppt f-each loop. Client program won't compile if implementation doesn't. 48

13 Stack iterar: linked-list implementation Stack iterar: array implementation impt java.util.iterar; public class Stack<Item> implements Iterable<Item>... public Iterar<Item> iterar() return new ListIterar(); private class ListIterar implements Iterar<Item> private Node current = ; public boolean hasnext() return current!= ; public void remove() /* not suppted */ public Item next() throw UnsupptedOperationException Item item = current.item; throw NoSuchElementException current = current.next; if no me items in iteration return item; 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 = n; public boolean hasnext() return i > 0; public void remove() /* not suppted */ public Item next() return s[--i]; current times of st the was it 49 s[] i n it was the st of time s Iteration: concurrent modification Q. What if client modifies the data structure while iterating? A. A fail-fast iterar throws a java.util.concurrentmodificationexception. Q. How detect concurrent modification? A. Count tal numr of push() and pop() operations in Stack. Save counts in *Iterar subclass upon creation. concurrent modification f (String s : stack) stack.push(s); If, when calling either next() hasnext(), the current counts do not equal the saved counts, throw exception. Algithms ROBERT SEDGEWICK KEVIN WAYNE BAGS, QUEUES, AND STACKS stacks resizing arrays queues generics iterars applications 51

14 PSA F this course, use our Stack and Queue implementations instead of Java s. Stack applications 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 Arithmetic expression evaluation Dijkstra's two-stack algithm demo Goal. Evaluate infix expressions using two stacks. value stack operar stack 1 ( 1 + ( ( ) * ( 4 * 5 ) ) ) + ( ( ) * ( 4 * 5 ) ) ) ( 1 + ( ( ) * ( 4 * 5 ) ) ) ( ( ) * ( 4 * 5 ) ) ) + 3 ) * ( 4 * 5 ) ) ) ) * ( 4 * 5 ) ) ) Two-stack algithm. [E. W. Dijkstra] Value: push on the value stack. Operar: push on the operar stack. Left parenthesis: igne. Right parenthesis: pop operar and two values apply operar the two values push the result value stack ) * ( 4 * 5 ) ) ) * ( 4 * 5 ) ) ) * ( 4 * 5 ) ) ) * * 5 ) ) ) * * 5 ) ) ) * * ) ) ) * ) ) ) 101 infix expression value stack operar stack (fully parenthesized) ( 1 + ( ( ) * ( 4 * 5 ) ) ) 55 operand operar 56

15 Arithmetic expression evaluation Crectness public class Evaluate public static void main(string[] args) Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty()) String s = StdIn.readString(); if (s.equals("(")) /* noop */ ; else if (s.equals("+")) ops.push(s); else if (s.equals("*")) ops.push(s); else if (s.equals(")")) String op = ops.pop(); if (op.equals("+")) vals.push(vals.pop() + vals.pop()); else if (op.equals("*")) vals.push(vals.pop() * vals.pop()); else vals.push(double.parsedouble(s)); StdOut.println(vals.pop()); % java Evaluate ( 1 + ( ( ) * ( 4 * 5 ) ) ) Q. Why crect? A. When algithm encounters an operar surrounded by two values within parentheses, it leaves the result on the value stack. as if the iginal input were: Repeating the argument: ( 1 + ( ( ) * ( 4 * 5 ) ) ) ( 1 + ( 5 * ( 4 * 5 ) ) ) ( 1 + ( 5 * 20 ) ) ( ) 101 Extensions. Me ops, precedence der, associativity Stack-based programming languages Observation 1. Dijkstra's two-stack algithm computes the same value if the operar occurs after the two values. ( 1 ( ( ) ( 4 5 * ) * ) + ) Observation 2. All of the parentheses are redundant! * * + Jan Lukasiewicz Botm line. Postfix "reverse Polish" notation. Applications. Postscript, Fth, calculars, Java virtual machine, 59

Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications

Algorithms. 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 information

Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications

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 information

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications. Is Polleverywhere working?

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications. Is Polleverywhere working? 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 http://algs4.cs.princen.edu stacks resizing arrays

More information

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE.

Algorithms. 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 information

Stacks and Queues. stacks dynamic resizing queues generics iterators applications. Stacks and queues

Stacks 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 information

4.3 Stacks and Queues

4.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 information

! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack.

! 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 information

4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API

4.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 information

TSP assignment next lecture

TSP 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

COMPUTER SCIENCE. Computer Science. 12. Stacks and Queues. Computer Science. An Interdisciplinary Approach. Section 4.3

COMPUTER 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 information

Stacks and Queues. !stacks!dynamic resizing!queues!generics!applications. Stacks and Queues

Stacks 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 information

14. Stacks and Queues

14. 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 information

14. Stacks and Queues

14. 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 information

14. Stacks and Queues

14. 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 information

2.6 Stacks and Queues

2.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 information

CS2012 Programming Techniques II

CS2012 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 information

Week 4 Stacks & Queues

Week 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 information

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

CMSC 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 information

4.3 Stacks, Queues, and Linked Lists

4.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 information

CSE 214 Computer Science II Stack

CSE 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 information

Basic Data Structures

Basic 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 information

Basic Data Structures 1 / 24

Basic 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 information

csci 210: Data Structures Stacks and Queues

csci 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 information

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS AND QUEUES. Problem Solving with Computers-II STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()

More information

CMSC 132: Object-Oriented Programming II. Stack and Queue

CMSC 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 information

Stacks, Queues (cont d)

Stacks, Queues (cont d) Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1

More information

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced

More information

Lecture 4 Stack and Queue

Lecture 4 Stack and Queue Lecture 4 Stack and Queue Bo Tang @ SUSTech, Spring 2018 Our Roadmap Stack Queue Stack vs. Queue 2 Stack A stack is a sequence in which: Items can be added and removed only at one end (the top) You can

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

Lecture Data Structure Stack

Lecture Data Structure Stack Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues The Bucharest University of Economic Studies Data Structures ADTs-Abstract Data Types Stacks and Queues Agenda Definition Graphical representation Internal interpretation Characteristics Operations Implementations

More information

1. Stack Implementation Using 1D Array

1. Stack Implementation Using 1D Array Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate

More information

Stacks Fall 2018 Margaret Reid-Miller

Stacks Fall 2018 Margaret Reid-Miller Stacks 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Today: Quiz 5 solutions Recursive add from last week (see SinglyLinkedListR.java) Stacks ADT (Queues on Thursday) ArrayStack

More information

LIFO : Last In First Out

LIFO : 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 information

PA3 Design Specification

PA3 Design Specification PA3 Teaching Data Structure 1. System Description The Data Structure Web application is written in JavaScript and HTML5. It has been divided into 9 pages: Singly linked page, Stack page, Postfix expression

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Stacks (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 information

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Lists. 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

Stack Abstract Data Type

Stack Abstract Data Type Stacks Chapter 5 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty To understand how Java implements a stack To learn how to implement a

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics HW Tips QT Creator dos & don ts ADTs Stack Example: Reverse-Polish Notation calculator Queue Event queues QT Creator A F E W W A R N I N

More information

1.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: 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 information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows: STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The

More information

Standard ADTs. Lecture 19 CS2110 Summer 2009

Standard ADTs. Lecture 19 CS2110 Summer 2009 Standard ADTs Lecture 19 CS2110 Summer 2009 Past Java Collections Framework How to use a few interfaces and implementations of abstract data types: Collection List Set Iterator Comparable Comparator 2

More information

Midterm Exam (REGULAR SECTION)

Midterm 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 information

Stacks and queues. CSCI 135: Fundamentals of Computer Science Keith Vertanen.

Stacks 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 information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked lists, allow insertion and deletion of elements

More information

Stacks and Queues. David Greenstein Monta Vista

Stacks 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 information

COS 226 Algorithms and Data Structures Fall Midterm

COS 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 information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

Java generics. h"p:// h"p://

Java generics. hp://  hp:// 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 information

CS W3134: Data Structures in Java

CS W3134: Data Structures in Java CS W3134: Data Structures in Java Lecture #10: Stacks, queues, linked lists 10/7/04 Janak J Parekh HW#2 questions? Administrivia Finish queues Stack/queue example Agenda 1 Circular queue: miscellany Having

More information

Queues. Stacks and Queues

Queues. 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 information

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1 CSE 2100 Data Structures and Algorithms... In Java Stacks 1 What is Stack A stack is a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle. Internet

More information

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Keeping 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 information

CS 211. Project 5 Infix Expression Evaluation

CS 211. Project 5 Infix Expression Evaluation CS 211 Project 5 Infix Expression Evaluation Part 1 Create you own Stack Class Need two stacks one stack of integers for the operands one stack of characters for the operators Do we need 2 Stack Classes?

More information

ADTs: Stacks and Queues

ADTs: Stacks and Queues Introduction to the Stack ADTs: Stack: a data structure that holds a collection of elements of the same type. - The elements are accessed according to LIFO order: last in, first out - No random access

More information

Linked List. April 2, 2007 Programming and Data Structure 1

Linked List. April 2, 2007 Programming and Data Structure 1 Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element

More information

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

16-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 information

Advanced Java Concepts Unit 3: Stacks and Queues

Advanced Java Concepts Unit 3: Stacks and Queues Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO).

More information

Week 6. Data structures

Week 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 information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 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 information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers)

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers) Comp 104:Operating Systems Concepts Revision Lectures (separate questions and answers) Today Here are a sample of questions that could appear in the exam Please LET ME KNOW if there are particular subjects

More information

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples: Ch. 8: ADTs: Stacks and Queues Abstract Data Type A data type for which: CS 8 Fall Jill Seaman - only the properties of the data and the operations to be performed on the data are specific, - not concerned

More information

Abstract Data Types and Java Generics. Fundamentals of Computer Science

Abstract 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 information

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CH 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 information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 03 / 31 / 2017 Instructor: Michael Eckmann Today s Topics Questions? Comments? finish RadixSort implementation some applications of stack Priority Queues Michael

More information

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types

More information

Building Java Programs

Building 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 information

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers)

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers) Comp 204: Computer Systems and Their Implementation Lecture 25a: Revision Lectures (separate questions and answers) 1 Today Here are a sample of questions that could appear in the exam Please LET ME KNOW

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

Implementing a Queue with a Linked List

Implementing a Queue with a Linked List CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 192] Implementing a Queue with a Linked List State representation: æ Data items are kept in a linked list. æ Pointer head points to

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. Stacks 1 Stacks The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. 2 Main stack operations Insertion and removal are defined by: push(e): inserts

More information

Data Structure. Recitation IV

Data Structure. Recitation IV Data Structure Recitation IV Topic Java Generics Java error handling Stack Lab 2 Java Generics The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello");

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 07 / 26 / 2016 Instructor: Michael Eckmann Today s Topics Comments/Questions? Stacks and Queues Applications of both Priority Queues Michael Eckmann - Skidmore

More information

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II

Adam 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 information

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Today s Topics ADTs Stack Example: Reverse-Polish Notation calculator Queue Example: Mouse Events Stacks New ADT: Stack stack.h template

More information

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1 Some Applications of Stack Spring Semester 2007 Programming and Data Structure 1 Arithmetic Expressions Polish Notation Spring Semester 2007 Programming and Data Structure 2 What is Polish Notation? Conventionally,

More information

CMSC Introduction to Algorithms Spring 2012 Lecture 7

CMSC Introduction to Algorithms Spring 2012 Lecture 7 CMSC 351 - Introduction to Algorithms Spring 2012 Lecture 7 Instructor: MohammadTaghi Hajiaghayi Scribe: Rajesh Chitnis 1 Introduction In this lecture we give an introduction to Data Structures like arrays,

More information

Chapter 2. Stack & Queues. M hiwa ahmad aziz

Chapter 2. Stack & Queues.   M hiwa ahmad aziz . Chapter 2 Stack & Queues www.raparinweb.com M hiwa ahmad aziz 1 Stack A stack structure with a series of data elements that Allows access to only the last item inserted. An item is inserted or removed

More information

Stacks and Queues. Fundamentals of Computer Science.

Stacks 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 information

Queues Fall 2018 Margaret Reid-Miller

Queues Fall 2018 Margaret Reid-Miller Queues 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Writing methods various classes that implement Lists. Methods using Lists and Big-O w/ ArrayList or LinkedLists Prove

More information

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion. 1. What is the full form of LIFO? The full form of LIFO is Last In First Out. 2. Give some examples for stack application. The examples of stack application are reverse a string, post fix evaluation, infix

More information

CSC 222: Computer Programming II. Spring 2005

CSC 222: Computer Programming II. Spring 2005 CSC 222: Computer Programming II Spring 2005 Stacks and recursion stack ADT push, pop, peek, empty, size ArrayList-based implementation, java.util.stack application: parenthesis/delimiter matching postfix

More information

Postfix (and prefix) notation

Postfix (and prefix) notation Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator

More information

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified. The Stack ADT Stacks Set of objects in which the location an item is inserted and deleted is prespecified Stacks! Insert in order! Delete most recent item inserted! LIFO - last in, first out Stacks 2 The

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 X Cynthia Lee Today s Topics ADTs Stack Example: Reverse-Polish Notation calculator Queue Example: Mouse Events Stacks New ADT: Stack stack.h template

More information

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50 Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

ITI Introduction to Computing II

ITI 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 information

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs 1 Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs Michael Albert michael.albert@cs.otago.ac.nz Keywords: abstract data type, collection, generic class type, stack 2 Collections

More information

cs2010: algorithms and data structures

cs2010: algorithms and data structures cs2010: algorithms and data structures Lecture 9: Priority Queues Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin Algorithms ROBERT SEDGEWICK KEVIN WAYNE 2.4 PRIORITY

More information

CS24 Week 4 Lecture 2

CS24 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 information

CSC 321: Data Structures. Fall 2012

CSC 321: Data Structures. Fall 2012 CSC 321: Data Structures Fall 2012 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

ITI Introduction to Computing II

ITI 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 information