top() Applications of Stacks

Similar documents
CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

End Semester Examination CSE, III Yr. (I Sem), 30002: Computer Organization

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Abstract Data Types (ADTs) Stacks. The Stack ADT ( 4.2) Stack Interface in Java

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

Data Structures Week #5. Trees (Ağaçlar)

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

CIS 121. Introduction to Trees

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Lecture 1: Introduction and Strassen s Algorithm

Elementary Data Structures. The Stack ADT ( 2.1.1) Applications of Stacks. Stacks, Queues, Vectors, Lists & Sequences Trees

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Announcements TREES II. Comparing Data Structures. Binary Search Trees. Red-Black Trees. Red-Black Trees 3/13/18

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

Last class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion

Homework 1 Solutions MA 522 Fall 2017

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

CS 11 C track: lecture 1

Lecture 5: Recursion. Recursion Overview. Recursion is a powerful technique for specifying funclons, sets, and programs

Analysis of Algorithms

Priority Queues. Binary Heaps

Data Structures and Algorithms Part 1.4

Computers and Scientific Thinking

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

EE260: Digital Design, Spring /16/18. n Example: m 0 (=x 1 x 2 ) is adjacent to m 1 (=x 1 x 2 ) and m 2 (=x 1 x 2 ) but NOT m 3 (=x 1 x 2 )

Chapter 3 Classification of FFT Processor Algorithms

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

Ones Assignment Method for Solving Traveling Salesman Problem

CMPT 125 Assignment 2 Solutions

Elementary Educational Computer

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Minimum Spanning Trees

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

n Haskell n Syntax n Lazy evaluation n Static typing and type inference n Algebraic data types n Pattern matching n Type classes

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

A Very Simple Approach for 3-D to 2-D Mapping

Analysis of Algorithms

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

DATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Python Programming: An Introduction to Computer Science

The Magma Database file formats

Reversible Realization of Quaternary Decoder, Multiplexer, and Demultiplexer Circuits

Math Section 2.2 Polynomial Functions

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

6.854J / J Advanced Algorithms Fall 2008

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

BOOLEAN MATHEMATICS: GENERAL THEORY

Last Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

From last week. Lecture 5. Outline. Principles of programming languages

Lecture 5. Counting Sort / Radix Sort

High-Order Language APPLICATION LEVEL HIGH-ORDER LANGUAGE LEVEL ASSEMBLY LEVEL OPERATING SYSTEM LEVEL INSTRUCTION SET ARCHITECTURE LEVEL

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

Priority Queues and Heaps (Ch 5.5) Huffman Coding Trees (Ch 5.6) Binary Search Trees (Ch 5.4) Lec 5: Binary Tree. Dr. Patrick Chan

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Solutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer

Today s objectives. CSE401: Introduction to Compiler Construction. What is a compiler? Administrative Details. Why study compilers?

How do we evaluate algorithms?

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

Τεχνολογία Λογισμικού

Stevina Dias* Sherrin Benjamin* Mitchell D silva* Lynette Lopes* *Assistant Professor Dwarkadas J Sanghavi College of Engineering, Vile Parle

Structuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software

Fast Fourier Transform (FFT) Algorithms

Data diverse software fault tolerance techniques

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

CS 111: Program Design I Lecture 19: Networks, the Web, and getting text from the Web in Python

The Implementation of Data Structures in Version 5 of Icon* Ralph E. Gr is wo Id TR 85-8

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Chapter 3. Floating Point Arithmetic

Introduction to Computing Systems: From Bits and Gates to C and Beyond 2 nd Edition

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Session Initiated Protocol (SIP) and Message-based Load Balancing (MBLB)

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III

Lower Bounds for Sorting

1 Enterprise Modeler

Data Structures and Algorithms. Analysis of Algorithms

5.3 Recursive definitions and structural induction

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

Lecture 3. RTL Design Methodology. Transition from Pseudocode & Interface to a Corresponding Block Diagram

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Transcription:

CS22 Algorithms ad Data Structures MW :00 am - 2: pm, MSEC 0 Istructor: Xiao Qi Lecture 6: Stacks ad Queues Aoucemets Quiz results Homework 2 is available Due o September 29 th, 2004 www.cs.mt.edu~xqicoursescs22 push(4) pop() top 2 top 4 NodeType * = ew NodeType; ->data = ; ->ext = top; top = ; = NULL; 4 Value stored i the top has to be retured before ode ca be deleted NodeType * = top; top = top->ext; it returvalue = ->data; delete ; top() Applicatios of Stacks top 4 retur top->data; Examiig programs to see if symbols balace properly. (Bracket matchig) Performig postfix calculatios. Performig ifix to postfix coversios. Fuctio calls (ad especially recursio) rely upo stacks.

Symbol Balacig A useful tool for checkig your code is to see if the (), {, ad [] symbols balace properly. For example the sequece [ ( ) ] is legal but the sequece [ ( ] ) is ot. The presece of oe misplaced symbol ca result i hudreds of worthless compiler diagostic errors! Symbol Balacig Algorithm The algorithm is simple ad efficiet: Make a empty stack. Read characters util ed of file (EOF). If the character is a opeig symbol ([{, push it oto the stack. If it is a closig symbol )], the if the stack is empty report a error. Otherwise pop the stack. If the symbol popped is ot the correspodig opeig symbol, report a error. At EOF, if the stack is ot empty report a error. Example Postfix Calculator class StackNode { private: it elemet; StackNode *ext; public: StackNode (cost it &theelemet, StackNode * = NULL) : elemet(theelemet), ext() { Push the { o the stack. Push the ( o the stack. See the ) ad pop the (. Everythig OK. Push the (, see the ), ad pop the (. OK. Push the (, see the ), ad pop the (. OK. Push the {, see the, ad pop the {. OK. See the, pop the origial {. All OK. What is postfix? It is the most efficiet method for represetig arithmetic expressios. With ifix (the method you are used to) you put operators betwee operads: a b. With postfix you put operators after operads: a b. There is ever ay eed to use () s with postfix otatio. There is ever ay ambiguity. Postfix Example This example is i ifix: a b * c (d * e f) * g I postfix this is: a b c * d e * f g * b*c a b*c d*e f d*e g * (f d*e) Postfix Calculator Algorithm The algorithm is simple ad efficiet O(N): Read i iput. If iput is a operad, push o stack. If iput is a operator, pop top two operads off stack, perform operatio, ad place result o stack. Example: a b c * Push a, b, ad the c o the stack. Pop c ad b, perform multiplicatio, ad push result. Pop (b*c) ad a, perform additio, ad push result. (a b*c) (g * (f d*e)) 2

Ifix to Postfix Coversio Surprisigly, oe oly eeds a stack to write a algorithm to covert a ifix expressio to a postfix expressio. It ca hadle the presece of () s. It is efficiet: O(N). Coversio Algorithm The algorithm is reasoably simple: Read ifix expressio as iput. If iput is operad, output the operad. If iput is a operator, -, *,, the pop ad output all operators of >= precedece. Push operator. If iput is (, the push. If iput is ), the pop ad output all operators util see a ( o the stack. Pop the ( without output. If o more iput the pop ad output all operators o stack. Coversio Example Details of Example Ifix: a b * c (d * e f) * g I postfix this is: a b c * d e * f g * Try to follow the algorithm to obtai the right postfix expressio. Output: Stack: ab c * d e * f g * * Arrows represet pop ad output ( * ( Arrows represet pop ad output ( * Fuctio Calls Example I almost all programmig laguages, callig a fuctio ivolves the use of a stack. Whe there is a fuctio call, all of the importat iformatio (values of variables etc.) is stored o a stack, ad cotrol is trasferred to the ew fuctio. This is especially importat durig recursio. Factorial of Retur Factorial of 2 2 * factorial() Factorial of 3 3 * factorial(2) Factorial of 4 4 * factorial(3) Factorial of * factorial(4) 2 6 24 log factorial (it ) { if ( <= ) retur ; else retur * factorial(-); 20 3

Stack Overflow Problems The factorial program is a example of tail recursio, where the recursive call occurs at the lie of the program. Probably exceed the stack limit i your operatig system Probably exceed the capacity of your itegers or eve doubles. Queues A queue is a waitig lie Both eds are used: oe for addig elemets ad oe for removig them. FIFO structure: First i, First out Queues A series of operatios executed o a queue Equeue(0) Equeue() dequeue Equeue() Equeue() dequeue 0 0 Queue ADT Data: A collectio of homogeeous elemets arraged i a sequece. Elemets are iserted to the ed ad removed from the Operatios: Equeue Dequeue IsEmpty El Implemetatio Details Cotiguous memory Usig a circular array Liked lists Usig a ode structure to store data ad a poiter to the ext ode: a chai of odes Queue Implemetatio via Arrays equeue() equeue(6) 4 4 6 if (!iffull()) { if (==size- ==-) { storage[0]= el; = 0; if ( == -) = 0; else { ; storage[]= el; 4

Queue Implemetatio via Arrays equeue() 2 4 3 2 4 3 if (!iffull()) { if (==size- ==-) { storage[0]= el; = 0; if ( == -) = 0; else { ; storage[]= el; Queue Implemetatio via Arrays 4 Value stored i the tmp has to be retured before is updated tmp = storage[]; if ( = ) = = -; else if ( = size ) = 0; else ; retur tmp == OR == 0 ad == size ; Queue Implemetatio via Arrays 4 4 Queue is empty tmp = storage[]; if ( = ) = = -; else if ( = size ) = 0; else ; retur tmp Queues usig Liked Lists Implemetatio of queues usig liked lists resembles the implemetatio of doubly liked lists with some operatios beig restricted Beig a queue we have oly oe isert operatio called equeue(). I may ways push is the same as isert i the We have also oe delete operatio called This operatio is the same as the operatio delete from the The other importat operatios i a stack, called () ad isempty(), do't modify the structure Pictorial view of a queue equeue() 2 2 NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL;

equeue() equeue() 2 2 NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; equeue() equeue() 2 2 NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; NULL 2 2 NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; 6

The value has to be "saved" to a orary variable before the ode ca be deleted 2 2 NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; 2 NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ;