Implementing and Using Stacks

Slides:



Advertisements
Similar presentations
Stacks.
Advertisements

© 2004 Goodrich, Tamassia Queues1. © 2004 Goodrich, Tamassia Queues2 The Queue ADT (§4.3) The Queue ADT stores arbitrary objects Insertions and deletions.
Queues1 Part-B2 Queues. Queues2 The Queue ADT (§4.3) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Stacks. Queues. Double-Ended Queues. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
Stacks. 2 Outline and Reading The Stack ADT (§4.2.1) Applications of Stacks (§4.2.3) Array-based implementation (§4.2.2) Growable array-based stack.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Data Structures Lecture 5 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Topic 15 Implementing and Using Stacks
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5)
Topic 15 Implementing and Using Stacks
Circular queue. Array-based Queue Use an array of size N in a circular fashion Three variables keep track of the front, rear, and size f index of the.
© 2004 Goodrich, Tamassia Queues1. © 2004 Goodrich, Tamassia Queues2 The Queue ADT (§4.3) The Queue ADT stores arbitrary objects Insertions and deletions.
Stacks. week 2a2 Outline and Reading The Stack ADT (§4.1) Applications of Stacks Array-based implementation (§4.1.2) Growable array-based stack Think.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Stacks and Linked Lists. Abstract Data Types (ADTs) An ADT is an abstraction of a data structure that specifies – Data stored – Operations on the data.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
CSC 211 Data Structures Lecture 23
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Queues by Dr. Bun Yue Professor of Computer Science CSCI 3333 Data Structures.
STACKS AND QUEUES 1. Outline 2  Stacks  Queues.
Lecture7: Queue Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Lecture6: Stacks Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Lecture 3 Queues Queues1. queue: – Retrieves elements in the order they were added. – First-In, First-Out ("FIFO") – Elements are stored in order of insertion.
Queues CSCI 3333 Data Structures. Acknowledgement  Dr. Bun Yue  Mr. Charles Moen  Dr. Wei Ding  Ms. Krishani Abeysekera  Dr. Michael Goodrich  Dr.
Queue. Avoid confusion Britain Italy 6 Applications of Queues Direct applications –Waiting lists, bureaucracy –Access to shared resources (e.g.,
Parasol Lab, Dept. CSE, Texas A&M University
Welcome to CSCE 221 – Data Structures and Algorithms
Queue. The Queue ADT Insertions and deletions follow the first-in first-out scheme Insertions are at the rear of the queue and removals are at the front.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
CH 5 : STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
CS 221 Analysis of Algorithms Data Structures. Portions of the following slides are from  Goodrich and Tamassia, Algorithm Design: Foundations, Analysis.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Stacks Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
© 2004 Goodrich, Tamassia Queues. © 2004 Goodrich, Tamassia Stacks2 The Queue ADT The Queue ADT stores arbitrary objects Insertions and deletions follow.
Queues1 © 2014 Goodrich, Tamassia, Goldwasser Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich,
Stacks (and Queues).
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Queues 5/11/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Stacks Stacks.
CSCI 3333 Data Structures Stacks.
Stacks.
Queues Queues Queues.
Queues 11/9/2018 6:28 PM Queues 11/9/2018 6:28 PM Queues.
Queues 11/9/2018 6:32 PM Queues.
Queues 11/16/2018 4:18 AM Queues 11/16/2018 4:18 AM Queues.
Queues 11/16/2018 4:19 AM Queues 11/16/2018 4:19 AM Queues.
Circular queue.
Queue.
Queues 11/22/2018 6:47 AM 5.2 Queues Queues Dr Zeinab Eid.
Stacks.
Stacks 12/7/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Queues 3/9/15 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Queues 12/30/2018 9:24 PM Queues 12/30/2018 9:24 PM Queues.
Recall What is a Data Structure Very Fundamental Data Structures
Stacks and Queues DSA 2013 Stacks n Queues.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Queues Jyh-Shing Roger Jang (張智星)
Stacks.
Copyright © Aiman Hanna All rights reserved
Topic 15 Implementing and Using Stacks
Lecture 8: Stacks, Queues
Stacks and Linked Lists
Presentation transcript:

Implementing and Using Stacks many slides taken from Mike Scott, UT Austin

Stacks Stacks are a straight forward and simple data structure Access is allowed only at one point of the structure, normally termed the top of the stack, so the operations are limited: push (add item to stack) pop (remove top item from stack) top (get top item without removing it) clear isEmpty size

Stack Operations Assume a simple stack for integers. Stack s = new Stack(); s.push(12); s.push(4); s.push( s.top() + 2 ); s.pop() s.push( s.top() ); //what are contents of stack?

Stack Operations Write a method to print out contents of stack in reverse order.

Common Stack Error Stack s = new Stack(); // put stuff in stack for(int i = 0; i < 7; i++) s.push( i ); // print out contents of stack // while emptying it for(int i = 0; i < s.size(); i++) System.out.println( s.pop() ); // Output? Why? // Crossover error

Corrected Version Stack s = new Stack(); // put stuff in stack for(int i = 0; i < 7; i++) s.push( i ); // print out contents of stack // while emptying it int limit = s.size(); for(int i = 0; i < limit; i++) System.out.println( s.pop() ); //or // while( !s.isEmpty() ) // System.out.println( s.pop() );

Balanced Symbol Checking In processing programs and working with computer languages there are many instances when symbols must be balanced { } , [ ] , ( ) A stack is useful for checking symbol balance. When a closing symbol is found it must match the most recent opening symbol of the same type. Algorithm?

Algorithm for Balanced Symbol Checking Make an empty stack read symbols until end of file if the symbol is an opening symbol push it onto the stack if it is a closing symbol do the following if the stack is empty report an error otherwise pop the stack. If the symbol popped does not match the closing symbol report an error At the end of the file if the stack is not empty report an error

Algorithm in practice list[i] = 3 * ( 44 - method( foo( list[ 2 * (i + 1) + foo( list[i - 1] ) ) / 2 *) - list[ method(list[0])]; Processing a file Tokenization: the process of scanning an input stream. Each independent chunk is a token. Tokens may be made up of 1 or more characters

Mathematical Calculations What is 3 + 2 * 4? 2 * 4 + 3? 3 * 2 + 4? The precedence of operators affects the order of operations. A mathematical expression cannot simply be evaluated left to right. A challenge when evaluating a program. Lexical analysis is the process of interpreting a program. Involves Tokenization What about 1 - 2 - 4 ^ 5 * 3 * 6 / 7 ^ 2 ^ 2

Infix and Postfix Expressions The way we are used to writing expressions is known as infix notation Postfix expression does not require any precedence rules 3 2 * 1 + is postfix of 3 * 2 + 1 evaluate the following postfix expressions and write out a corresponding infix expression: 2 3 2 4 * + * 1 2 3 4 ^ * + 1 2 - 3 2 ^ 3 * 6 / + 2 5 ^ 1 -

Evaluation of Postfix Expressions Easy to do with a stack given a proper postfix expression: get the next token if it is an operand push it onto the stack else if it is an operator pop the stack for the right hand operand pop the stack for the left hand operand apply the operator to the two operands push the result onto the stack when the expression has been exhausted the result is the top (and only element) of the stack

Infix to Postfix Convert the following equations from infix to postfix: 2 ^ 3 ^ 3 + 5 * 1 2 3 3 ^ ^ 5 1 * + 11 + 2 - 1 * 3 / 3 + 2 ^ 2 / 3 11 2 + 1 3 * 3 / - 2 2 ^ 3 / + Problems: parentheses in expression

Infix to Postfix Conversion Requires operator precedence parsing algorithm parse v. To determine the syntactic structure of a sentence or other utterance Operands: add to expression Close parenthesis: pop stack symbols until an open parenthesis appears Operators: Pop all stack symbols until a symbol of lower precedence appears. Then push the operator End of input: Pop all remaining stack symbols and add to the expression

Simple Example Infix Expression: 3 + 2 * 4 PostFix Expression: Operator Stack:

Simple Example Infix Expression: + 2 * 4 PostFix Expression: 3 Operator Stack:

Simple Example Infix Expression: 2 * 4 PostFix Expression: 3 Operator Stack: +

Simple Example Infix Expression: * 4 PostFix Expression: 3 2 Operator Stack: +

Simple Example Infix Expression: 4 PostFix Expression: 3 2 Operator Stack: + *

Simple Example Infix Expression: PostFix Expression: 3 2 4 Operator Stack: + *

Simple Example Infix Expression: PostFix Expression: 3 2 4 * Operator Stack: +

Simple Example Infix Expression: PostFix Expression: 3 2 4 * + Operator Stack:

Example 1 - 2 ^ 3 ^ 3 - ( 4 + 5 * 6 ) * 7 Show algorithm in action on above equation

Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine Validate XML Indirect applications Auxiliary data structure for algorithms Component of other data structures

Method Stack in the JVM The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack When a method is called, the JVM pushes on the stack a frame containing Local variables and return value Program counter, keeping track of the statement being executed When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack Allows for recursion main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } bar PC = 1 m = 6 foo PC = 3 j = 5 k = 6 main PC = 2 i = 5

Implementing a stack need an underlying collection to hold the elements of the stack 2 basic choices array (native or ArrayList) linked list array implementation linked list implementation Some of the uses for a stack are much more interesting than the implementation of a stack

Array-based Stack Algorithm size() return t + 1 Algorithm pop() if isEmpty() then throw EmptyStackException else t  t  1 return S[t + 1] A simple way of implementing the Stack ADT uses an array We add elements from left to right A variable keeps track of the index of the top element … S 1 2 t

Queues

Queues Closely related to Stacks Like a line In Britain people don’t “get in line” they “queue up”. Queues are a first in first out data structure FIFO (or LILO, but that sounds a bit silly) Add items to the end of the queue Access and remove from the front Used extensively in operating systems Queues of processes, I/O requests, and much more

Queue operations add(Object item) Object get() Object remove() a.k.a. enqueue(Object item) Object get() a.k.a. Object front() Object remove() a.k.a. Object dequeue() boolean isEmpty() Specify in an interface, allow varied implementations

Queue Example Operation Output Q enqueue(5) – (5) enqueue(3) – (5, 3) dequeue() 5 (3) enqueue(7) – (3, 7) dequeue() 3 (7) front() 7 (7) dequeue() 7 () dequeue() “error” () isEmpty() true () enqueue(9) – (9) enqueue(7) – (9, 7) size() 2 (9, 7) enqueue(3) – (9, 7, 3) enqueue(5) – (9, 7, 3, 5) dequeue() 9 (7, 3, 5)

Applications of Queues Direct applications Waiting lists, bureaucracy Access to shared resources (e.g., printer) Multiprogramming Indirect applications Auxiliary data structure for algorithms Component of other data structures

Implementation Array-based Queue Use an array of size N in a circular fashion Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Array location r is kept empty normal configuration Q 1 2 r f wrapped-around configuration Q 1 2 f r

Queue Operations We use the modulo operator (remainder of division) Algorithm size() return (N - f + r) mod N Algorithm isEmpty() return (f = r) Q 1 2 r f Q 1 2 f r

Queue Operations (cont.) Algorithm enqueue(o) if size() = N  1 then throw FullQueueException else Q[r]  o r  (r + 1) mod N Operation enqueue throws an exception if the array is full This exception is implementation-dependent Q 1 2 r f Q 1 2 f r

Queue Operations (cont.) Algorithm dequeue() if isEmpty() then throw EmptyQueueException else o  Q[f] f  (f + 1) mod N return o Operation dequeue throws an exception if the queue is empty This exception is specified in the queue ADT Q 1 2 r f Q 1 2 f r

Queue Interface in Java public interface Queue { public int size(); public boolean isEmpty(); public Object front() throws EmptyQueueException; public void enqueue(Object o); public Object dequeue() throws EmptyQueueException; } Java interface corresponding to our Queue ADT Requires the definition of class EmptyQueueException No corresponding built-in Java class, however there is PriorityQueue

Application: Round Robin Schedulers We can implement a round robin scheduler using a queue, Q, by repeatedly performing the following steps: e = Q.dequeue() Service element e Q.enqueue(e) The Queue Shared Service 1 . Deque the next element 3 Enqueue the serviced element 2 Service the

Implementing a Queue Given the internal storage container and choice for front and back of queue what are the Big O of the queue operations? ArrayList LinkedList LinkedList (Singly Linked) (Doubly Linked) enqueue front dequeue isEmpty

Priority Queue Implementation Sequence-based Priority Queue Implementation with an unsorted list Performance: insert takes O(1) time since we can insert the item at the beginning or end of the sequence removeMin and min take O(n) time since we have to traverse the entire sequence to find the smallest key Implementation with a sorted list Performance: insert takes O(n) time since we have to find the place where to insert the item removeMin and min take O(1) time, since the smallest key is at the beginning 4 5 2 3 1 1 2 3 4 5

Priority Queue Applications Priority-based OS process scheduler