14. Stacks and Queues
|
|
- Basil Clarke
- 6 years ago
- Views:
Transcription
1 Section Data types and data structures Data types APIs Clients Strawman implementation Linked lists Implementations Set of values. Set of operations on those values. Some are built in Java: int, double, String,... Most are : Complex, Picture, Charge,... Data structures Represent data. Represent relationships among data. Some are built in Java: D arrays, 2D arrays,... Most are : linked list, circular list, tree,... Design challenge f every data type: Which data structure use? Resource : How much memy is needed? Resource 2: How much time do data-type use? 4
2 Stack and Queue APIs Example of stack operations A collection is an ADT whose values are a multiset of items, all of the same type. Two fundamental collection ADTs differ in just a detail of the specification of their operations. Add the ginning Stack operations Add an item the collection. Remove and return the item most recently added (LIFO). Test if the collection is empty. Return the size of the collection. Take from the ginning Last In Out Stacks and queues both arise naturally in countless applications. A key characteristic. No limit on the size of the collection. Queue operations Add an item the collection. Remove and return the item least recently added (FIFO). Test if the collection is empty. Return the size of the collection. Take from the ginning In Out Add the end Push. Add an item the collection. Pop. Remove and return the item most recently added. push is pop stack contents after operation push the ginning pop from the ginning push the ginning pop from the ginning Last In Out is 6 Example of queue operations dequeue from the ginning Parameterized data types Goal. Simple, safe, and clear client code f collections of any type of data. Enqueue. Add an item the collection. Dequeue. Remove and return the item least recently added. In Out Java approach: Parameterized data types (generics) Use placeholder type name in definition. Substitute concrete type f placeholder in clients. stay tuned f examples public class Stack<Item> enqueue is dequeue queue contents after operation dequeue from the ginning enqueue at the end enqueue at the end is 7 Stack API Queue API Stack<Item>() create a stack of objects, all of type Item void push(item item) add item stack Item pop() remove and return the item most recently pushed boolean isempty() is the stack empty? int size() # of objects on the stack public class Queue<Item> Queue<Item>() create a queue of objects, all of type Item void enqueue(item item) add item queue Item dequeue() remove and return the item least recently enqueued boolean isempty() is the queue empty? int size() # of objects on the queue 8
3 Perfmance specifications Challenge. Provide guarantees on perfmance. Goal. Simple, safe, clear, and efficient client code. Perfmance specifications All operations are constant-time. Memy use is proptional the size of the collection, when it is nonempty. No limits within the code on the collection size. Java. Any implementation of the API implements the stack/queue abstractions. Typically required f client code scalable APIs Clients Strawman implementation Linked lists Implementations RS+KW. Implementations do meet perfmance specs do implement the abstractions. 9 APIs Clients Strawman implementation Linked lists Implementations Stack and queue applications Queues -come--served resource allocation. Asynchronous data transfer (StdIn, StdOut). Dispensing requests on a shared resource (printer, process). Simulations of the real wld (guitar string, traffic analysis, ) Stacks Last-come--served processes (browser, ). Function calls in programming languages. Basic mechanism in interpreters, compilers
4 Queue client example: Read all strings from StdIn in an array Queue client example: Read all strings from StdIn in an array Challenge Can t sre strings in array fe creating the array. Can t create the array without knowing how many strings are in the input stream. Can t know how many strings are in the input stream without reading them all. Solution: Use a Queue<String>. public class QEx Note: StdIn has this functionality public static String[] readallstrings() // See next slide. public static void main(string[] args) String[] wds = readallstrings(); f (int i = 0; i < wds.length; i++) StdOut.println(wds[i]); % me moby.txt moby dick herman melville call me ishmael some years ago never mind how long precisely having little no money % java QEx < moby.txt moby dick herman melville call me ishmael some years 3 Solution: Use a Queue<String>. Sre strings in the queue. Get the size when all have en read from StdIn. Create an array of size. Copy the strings in the array. public class QEx public static String[] readallstrings() Queue<String> q = new Queue<String>(); q.enqueue(stdin.readstring()); int N = q.size(); String[] wds = new String[N]; f (int i = 0; i < N; i++) wds[i] = q.dequeue(); return wds; public static void main(string[] args) String[] wds = readallstrings(); f (int i = 0; i < wds.length; i++) StdOut.println(wds[i]); 4 Stack example: "Back" butn in a browser Auboxing Typical scenario Visit a page. Click a link aher page. Click a link aher page. Click a link aher page. Click "back" butn. Click "back" butn. Click "back" butn. Challenge. Use a primitive type in a parameterized ADT. Wrapper types Each primitive type has a wrapper reference type. Wrapper type has larger set of operations than primitive type. Example: Integer.parseInt(). Values of wrapper types are objects. Wrapper type can used in a parameterized ADT. primitive type int long double boolean wrapper type Integer Long Double Boolean Auboxing. Aumatic cast from primitive type wrapper type. Au-unboxing. Aumatic cast from wrapper type primitive type Simple client code (no casts) Stack<Integer> stack = new Stack<Integer>(); stack.push(7); // Aubox (int -> Integer) int a = stack.pop(); // Au-unbox (Integer -> int) 6
5 Stack client example: Postfix expression evaluation Postfix arithmetic expression evaluation Algithm Infix. Standard way of writing arithmetic expressions, using parentheses f precedence. While input stream is nonempty, read a ken. Value: Push on the stack. Operar: Pop operand(s), apply operar, push the result. Example. ( + ( ( ) * ( 4 * ) ) ) = ( + ( * 20) ) = 0 Postfix. Write operar after operands (instead of in tween them). Example * * + also called "reverse Polish" ation (RPN) Jan ukasiewicz = 4 * * + Remarkable fact. No parentheses are needed! * * + There is only one way parenthesize a postfix expression. (2+3)4 * * + ((2+3)*(4*))+ (+((2+3)*(4*))) find operar, convert infix, enclose in () iterate, treating suxpressions in parentheses as amic Next. With a stack, postfix expressions are easy evaluate Made slide rule obsolete (!) 4 * * + HP-3 (972) handheld calcular. "Enter" means "push". No parentheses Stack client example: Postfix expression evaluation public class Postfix public static void main(string[] args) Stack<Double> stack = new Stack<Double>(); String ken = StdIn.readString(); if (ken.equals("*")) stack.push(stack.pop() * stack.pop()); else if (ken.equals("+")) stack.push(stack.pop() + stack.pop()); else if (ken.equals("-")) stack.push(- stack.pop() + stack.pop()); else if (ken.equals("/")) stack.push((.0/stack.pop()) * stack.pop()); else if (ken.equals("sqrt")) stack.push(math.sqrt(stack.pop())); else stack.push(double.parsedouble(ken)); StdOut.println(stack.pop()); 2 = 20 = 0 = 00 8 Real-wld stack application: PostScript PostScript (Warnock-Geschke, 980s): A turtle with a stack. % java Postfix * * + 0 % java Postfix sqrt + 2 / Postfix program code (push literals; functions pop arguments). Add commands drive virtual graphics machine. Add loops, conditionals, functions, types, fonts, strings. push(00) PostScript code + move line line line 00 call "move" (takes args from stack) define a path draw the path A simple virtual machine, but a y Perspective stroke 300 Easy specify published page. Easy implement on various specific printers. Revolutionized wld of publishing. Easy add operars of all sts. Can do infix with two stacks (see text). Could output TOY program. Indicative of how Java compiler wks. Aher stack machine: The JVM ( Java Virtual Machine)! 9 20
6 APIs Clients Strawman implementation Linked lists Implementations APIs Clients Strawman implementation Linked lists Implementations Strawman ADT f pushdown stacks Strawman implementation: Instance variables and construcr Warmup: simplify the ADT Implement only f items of type String. Have client provide a stack capacity in the construcr. Data structure choice. Use an array hold the collection. construcr values public class StrawStack private String[] a; private int N = 0; a[0] a[] a[2] items on stack Strawman API public class StrawStack StrawStack(int max) void push(string item) String pop() create a stack of capacity max add item stack return the string most recently pushed public StrawStack(int max) a = new String[max]; N "upside down" representation of boolean isempty() is the stack empty? int size() numr of strings on the stack Rationale. Allows us represent the collection with an array of strings
7 Strawman stack implementation: Test client TEQ on stacks public static void main(string[] args) int max = Integer.parseInt(args[0]); StrawStack stack = new StrawStack(max); String item = StdIn.readString(); if (item.equals("-")) stack.push(item); else StdOut.print(stack.pop()); StdOut.println(); construcrs % me.txt is % java StrawStack 20 <.txt Q. Can we always insert pop() commands make items come out in sted der? Example Example Example What we expect, once the implementation is done TEQ on stacks Strawman implementation: Methods Q. Can we always insert pop() commands make items come out in sted der? Methods define data-type operations (implement APIs). construcrs Example Example Example public class StrawStack public boolean isempty() return (N == 0); public void push(object item) a[n++] = item; N after push() A. No. Example. 6 no way f popped fe 6 public String pop() return a[--n]; public int size() return N; all constant-time one-liners! N N after pop() Note. In a queue, they always come out in the der they came in
8 Strawman pushdown stack implementation Trace of strawman stack implementation (array representation) public class StrawStack private String[] a; private int N = 0; public StrawStack(int max) a = new String[max]; public boolean isempty() return (N == 0); public void push(string item) a[n++] = item; public String pop() return a[--n]; public int size() return N; public static void main(string[] args) int max = Integer.parseInt(args[0]); StrawStack stack = new StrawStack(max); String item = StdIn.readString(); if (item.compareto("-")!= 0) stack.push(item); else StdOut.print(stack.pop()); StdOut.println(); construcr % me.txt is % java StrawStack 20 <.txt 29 stack contents after operation push is pop a[0] a[] a[2] a[3] a[4] a[] a[6] a[7] a[8] a[9] a[0] a[] a[2] a[3] a[4] a[] a[6] a[7] a[8] a[9] N Significant wasted space when stack size is near the capacity (typical). is 30 Benchmarking the strawman stack implementation StrawStack implements a fixed-capacity collection haves like a stack if the data fits. It does implement the stack API meet the perfmance specifications. Stack API StrawStack wks only f strings Perfmance specifications public class Stack<Item> Stack<Item>() void push(item item) Item pop() create a stack of objects, all of type Item add item stack boolean isempty() is the stack empty? int size() remove and return the item most recently pushed # of objects on the stack All operations are constant-time. Memy use is proptional the size of the collection, when it is nonempty. No limits within the code on the collection size. StrawStack requires client provide capacity APIs Clients Strawman implementation Linked lists Implementations Nice try, but need a new data structure. 3
9 Data structures: sequential vs. linked Sequential data structure Put objects next one aher. TOY: consecutive memy cells. Java: array of objects. Fixed size, arbitrary access. i th element Array at C0 addr value C0 "Alice" C "Bob" C2 "Carol" C3 Linked list at C4 addr value C0 "Carol" C null C2 C3 APIs Clients Strawman implementation Linked lists Implementations Linked data structure Associate with each object a link aher one. TOY: link is memy address of next object. Java: link is reference next object. Variable size, sequential access. next element Overlooked by novice programmers. Flexible, widely used method f ganizing data. C4 C C6 C7 C8 C9 CA CB C4 C C6 C7 C8 C9 CA CB "Alice" CA "Bob" C0 34 Simplest singly-linked data structure: linked list Singly-linked data structures Linked list A recursive data structure. Def. A linked list is null a reference a node. Def. A node is a data type contains a reference a node. Unwind recursion: A linked list is a sequence of nodes. private class Node private String item; private Node next; Even with just one link ( Linked list (this lecture) ) a wide variety of data structures are possible. Tree Rho Representation Use a private nested class Node implement the node abstraction. F simplicity, start with nodes having two values: a String and a Node. Circular list (TSP) General case A linked list "Alice" "Bob" "Carol" item next null Multiply linked structures: many me possibilities! From the point of view of a particular object, all of these structures look the same. 3 36
10 Building a linked list List processing code Node third = new Node(); third.item = "Carol"; third.next = null; Node second = new Node(); second.item = "Bob"; second.next = third; Node = new Node();.item = "Alice";.next = second; third C0 second CA C4 addr C0 C C2 C3 C4 C C6 C7 C8 value "Carol" null "Alice" CA Standard operations f processing data structured as a singly-linked list Add a node at the ginning. Remove and return the node at the ginning. Add a node at the end (requires a reference the last node). Traverse the list (visit every node, in sequence). An operation calls f a doubly-linked list (slightly yond our scope) Remove and return the node at the end. second third C9 CA "Bob" "Alice" "Bob" "Carol" CB C0 null List processing code: Remove and return the item List processing code: Add a new node at the ginning Goal. Remove and return the item in a linked list. Goal. Add item a linked list. item "Dave" "Alice" "Bob" "Carol" "Alice" "Bob" "Carol" item =.item; item "Alice" "Alice" "Bob" "Carol" Node second = ; second "Alice" "Bob" "Carol" second =.next; item "Alice" "Alice" "Bob" "Carol" = new Node(); "Alice" "Bob" "Carol" available f garbage collection second return item; item "Alice" "Bob" "Carol".item = item;.next = second; "Dave" "Alice" "Bob" "Carol" 39 40
11 List processing code: Traverse a list Goal. Visit every node on a linked list. TEQ on linked lists Q. What is the effect of the following code (-so-easy question)? Node x = ; while (x!= null) StdOut.println(x.item); x = x.next; x "Alice" "Bob" "Carol" StdOut Alice Bob Carol Node list = null; Node old = list; list = new Node(); list.item = StdIn.readString(); list.next = old; f (Node t = list; t!= null; t = t.next) StdOut.println(t.item); 4 42 TEQ on linked lists Q. What is the effect of the following code (-so-easy question)? TEQ 2 on stacks Q. Give code uses a stack print the strings from StdIn on StdOut, in reverse der. Node list = null; Node old = list; list = new Node(); list.item = StdIn.readString(); list.next = old; f (Node t = list; t!= null; t = t.next) StdOut.println(t.item); list old list old list A. Prints the strings from StdIn on StdOut, in reverse der. Note. Better use a stack
12 TEQ 2 on stacks TEQ 2 on linked lists Q. Give code uses a stack print the strings from StdIn on StdOut, in reverse der. Q. What is the effect of the following code (-so-easy question)? A. Stack<String> stack = new Stack<String>(); stack.push(stdin.readstring()); while (!stack.isempty()) StdOut.println(stack.pop()); Node list = new Node(); list.item = StdIn.readString(); Node last = list; last.next = new Node(); last = last.next; last.item = StdIn.readString(); 4 46 TEQ 2 on linked lists Q. What is the effect of the following code (-so-easy question)? Node list = new Node(); list.item = StdIn.readString(); Node last = list; last.next = new Node(); last = last.next; last.item = StdIn.readString(); A. Puts the strings from StdIn on a linked list, in the der they are read (assuming at least one string). Note. Better use a queue, in most applications. list list list last last last APIs Clients Strawman implementation Linked lists Implementations In this course, we restrict use of linked lists data-type implementations 47
13 ADT f pushdown stacks: review A pushdown stack is an idealized model of a LIFO srage mechanism. An ADT allows us write Java programs use and manipulate pushdown stacks. APIs Clients Strawman implementation Linked lists Implementations API Perfmance specifications public class Stack<Item> Stack<Item>() void push(item item) add item stack Item pop() boolean isempty() is the stack empty? int size() create a stack of objects, all of type Item remove and return the item most recently pushed # of objects on the stack All operations are constant-time. Memy use is proptional the size of the collection, when it is nonempty. No limits within the code on the collection size. 0 Pushdown stack implementation: Instance variables and construcr Stack implementation: Test client Data structure choice. Use a linked list hold the collection. public class Stack<Item> private Node = null; private int N = 0; private class Node private Item item; private Node next; use in place of concrete type objects on stack construcr construcrs public static void main(string[] args) Stack<String> stack = new Stack<String>(); String item = StdIn.readString(); if (item.equals("-")) stack.push(item); else System.out.print(stack.pop()); StdOut.println(); % me.txt is Annoying exception ( a problem here). Can't declare an array of Item objects (don't ask why). Need cast: Item[] a = (Item[]) new Object[N] What we expect, once the implementation is done. % java Stack <.txt 2
14 Stack implementation: Methods Stack implementation Methods define data-type operations (implement the API). public class Stack<Item> public boolean isempty() return == null; public void push(item item) Node second = ; = new Node();.item = item;.next = second; N++; public Item pop() Item item =.item; =.next; N--; return item; public int size() return N; add a new node the ginning of the list remove and return item on list instance variable second construcrs local variable in push() 3 public class Stack<Item> private Node = null; private int N = 0; private class Node private Item item; private Node next; public boolean isempty() return == null; public void push(item item) Node second = ; = new Node();.item = item;.next = second; N++; public Item pop() Item item =.item; =.next; N--; return item; public int size() return N; public static void main(string[] args) // See earlier slide nested class % me.txt is % java Stack <.txt 4 Trace of stack implementation (linked list representation) Benchmarking the stack implementation push is pop Pop from the ginning Push the ginning is Stack implements the stack abstraction. It does implement the API and meet the perfmance specifications. Stack API Perfmance specifications public class Stack<Item> Stack<Item>() void push(item item) Item pop() All operations are constant-time. Memy use is proptional the size of the collection, when it is nonempty. No limits within the code on the collection size. Made possible by linked data structure. create a stack of objects, all of type Item add item stack boolean isempty() is the stack empty? int size() remove and return the item most recently pushed # of objects on the stack dequeue(): same code as pop() enqueue(): slightly me complicated, like TEQ 2 Also possible implement the queue abstraction with a singly-linked list (see text). 6
15 Summary push the pop from the ginning ginning Stacks and queues Fundamental collection abstractions. Differ only in der in which items are removed. Perfmance specifications: Constant-time f all operations and space proptional numr of objects. stack Last In Out dequeue from the ginning In queue Out enqueue at the end Linked structures APIs Clients Strawman implementation Linked lists Implementations Fundamental alternative sequential structures. Enable implementations of the stack/queue abstractions meet perfmance specifications. Next: Symbol tables 7 Section 4.3
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 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 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 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 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 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 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 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 informationAlgorithms. 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 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 informationAlgorithms. 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 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 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 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 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 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 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 information4.3: Linked Structures
Linked vs. Sequential Allocation 4.3: Linked Structures "The name of the song is called 'Haddocks' Eyes.' " "Oh, that's the name of the song, is it?" Alice said, trying to feel interested. "No, you don't
More informationPA3 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 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 informationThe Stack and Queue Types
The Stack and Queue Types Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Programming Principle of the Day Do the simplest thing that could possibly work A good
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 informationEC8393FUNDAMENTALS 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 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 informationCS 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 informationQueues 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 informationSTACKS 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 informationCOMPUTER SCIENCE. 15. Symbol Tables. Section 4.4.
COMPUTER SCIENCE S E D G E W I C K / W A Y N E 15. Symbol Tables Section 4.4 http://introcs.cs.princeton.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 15.Symbol Tables APIs and clients A design challenge
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 informationCosc 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 informationLecture 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 informationStacks 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 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 informationLecture P5: Abstract Data Types
Review Lecture P5: Abstract Data Types Data type: Set of values and collection of operations on those values. Example: int Set of values: between -32,767 and 32,767 (minimum limits). Operations: +, -,
More informationLinked 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 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 informationAdvanced 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 informationMIDTERM EXAMINATION Spring 2010 CS301- Data Structures
MIDTERM EXAMINATION Spring 2010 CS301- Data Structures Question No: 1 Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the
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 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 informationCSC 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 informationMULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR
STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM
More informationAbstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1
Abstract Data Types Stack January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract data types and data structures An Abstract Data Type (ADT) is: A collection of data Describes what data are stored but
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 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! 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 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 informationStack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.
STACK Stack ADT 2 A stack is an abstract data type based on the list data model All operations are performed at one end of the list called the top of the stack (TOS) LIFO (for last-in first-out) list is
More informationSTACKS. 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 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 informationLists, 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 informationInformation Science 2
Information Science 2 - Basic Data Structures- Week 02 College of Information Science and Engineering Ritsumeikan University Today s class outline l Basic data structures: Definitions and implementation
More informationStacks. 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 informationCS.15.A.SymbolTables.API. Alice
15.Symbol Tables APIs and clients A design challenge Binary search trees Implementation Analysis 15. Symbol Tables Section 4.4 http://introcs.cs.princeton.edu CS.15.A.SymbolTables.API FAQs about sorting
More informationFirst Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...
First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms.... Q1) What are some of the applications for the tree data structure? Q2) There are 8, 15, 13, and
More informationThe 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 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 informationArrays and Linked Lists
Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every
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 informationProgramming 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 informationinfix 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 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 informationRevision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,
[1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n
More informationPostfix (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 informationCOMPUTER SCIENCE. Computer Science. 13. Symbol Tables. Computer Science. An Interdisciplinary Approach. Section 4.4.
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.4 ROBERT SEDGEWICK
More informationProgramming 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 informationInsertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue
Queues CSE 2011 Fall 2009 9/28/2009 7:56 AM 1 Queues: FIFO Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Applications,
More information#06 More Structures LIFO FIFO. Contents. Queue vs. Stack 3. Stack Operations. Pop. Push. Stack Queue Hash table
Contents #06 More Structures -07 FUNDAMENTAL PROGRAMMING I Stack Queue Hash table DEPARTMENT OF COMPUTER ENGINEERING, PSU v. Queue vs. Stack Stack Operations IN IN OUT Push: add an item to the top Pop:
More informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
More informationCS 106B Lecture 5: Stacks and Queues
CS 106B Lecture 5: Stacks and Queues Monday, July 3, 2017 Programming Abstractions Summer 2017 Stanford University Computer Science Department Lecturer: Chris Gregg reading: Programming Abstractions in
More information12 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 informationUNIT 6A Organizing Data: Lists. Last Two Weeks
UNIT 6A Organizing Data: Lists 1 Last Two Weeks Algorithms: Searching and sorting Problem solving technique: Recursion Asymptotic worst case analysis using the big O notation 2 1 This Week Observe: The
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 informationDATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.
DATA STRUCUTRES A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. An algorithm, which is a finite sequence of instructions, each of which
More informationCS6202 - PROGRAMMING & DATA STRUCTURES I Unit IV Part - A 1. Define Stack. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. It is an abstract data type
More informationComputer 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 informationUNIT 6A Organizing Data: Lists Principles of Computing, Carnegie Mellon University
UNIT 6A Organizing Data: Lists Carnegie Mellon University 1 Data Structure The organization of data is a very important issue for computation. A data structure is a way of storing data in a computer so
More informationProblem with Scanning an Infix Expression
Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix
More informationProgramming 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 informationList, Stack, and Queues
List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of
More informationCSE 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 informationUNIT 3
UNIT 3 Presentation Outline Sequence control with expressions Conditional Statements, Loops Exception Handling Subprogram definition and activation Simple and Recursive Subprogram Subprogram Environment
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 informationLecture 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 informationCS 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 informationWentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.
Lecture 11 1 More Data Structures In this lecture we will use a linked list to implement two abstract data types (ADT) An ADT provides the interface, or what a data structure does We can then use code
More informationCSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills
CSCI 136 Data Structures & Advanced Programming Lecture 14 Fall 2018 Instructor: Bills Announcements Mid-Term Review Session Monday (10/15), 7:00-8:00 pm in TPL 203 No prepared remarks, so bring questions!
More information3137 Data Structures and Algorithms in C++
3137 Data Structures and Algorithms in C++ Lecture 3 July 12 2006 Shlomo Hershkop 1 Announcements Homework 2 out tonight Please make sure you complete hw1 asap if you have issues, please contact me will
More informationWhat is an algorithm?
Announcements CS 142 Stacks & Queues Program 3 has been assigned due 10/6 by 11:55pm Program details on website 2 Creating new Data Structures We ve used objects to create new data types such as Point,
More informationLecture No.04. Data Structures
Lecture No.04 Data Structures Josephus Problem #include "CList.cpp" void main(int argc, char *argv[]) { CList list; int i, N=10, M=3; for(i=1; i
More informationA linear-list Data Structure where - addition of elements to and - removal of elements from are restricted to the first element of the list.
A linear-list Data Structure where - addition of elements to and - removal of elements from are restricted to the first element of the list. the first element of the list a new element to (the Top of)
More informationStack 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 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 informationChapter 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 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 informationCS 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 informationProblem with Scanning an Infix Expression
Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix
More information