Stacks. Revised based on textbook author s notes.

Similar documents
-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

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

Stack Abstract Data Type

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

Lecture 12 ADTs and Stacks

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

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

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

STACKS AND QUEUES. Problem Solving with Computers-II

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

Stack and Its Implementation

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

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT

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

March 13/2003 Jayakanth Srinivasan,

Stacks Fall 2018 Margaret Reid-Miller

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

CISC-235. At this point we fnally turned our atention to a data structure: the stack

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

Formal Languages and Automata Theory, SS Project (due Week 14)

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.

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

PA3 Design Specification

Lecture Data Structure Stack

Stacks and their Applications

The Stack and Queue Types

Lab 7 1 Due Thu., 6 Apr. 2017

CS 211 Programming Practicum Spring 2017

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

Lecture 8: Simple Calculator Application

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

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Foundations of Data Structures

Data structure and algorithm in Python

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

CS 211 Programming Practicum Spring 2018

Data Structures Week #3. Stacks

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Queues Fall 2018 Margaret Reid-Miller

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

Project 1: Implementation of the Stack ADT and Its Application

infix expressions (review)

CSE 143. Lecture 4: Stacks and Queues

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

Programming Abstractions

Stacks Calculator Application. Alexandra Stefan

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

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

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

BBM 201 DATA STRUCTURES

Linear Data Structure

1. Stack Implementation Using 1D Array

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

CS 206 Introduction to Computer Science II

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

Problem with Scanning an Infix Expression

Stacks. CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack.

1. Algorithm. Data Structures & Algorithms. How many times you weight? Algo 2 : Half Cutting. How many times you weight? Algo.1 :Two coins at a time

CS 206 Introduction to Computer Science II

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Stacks, Queues (cont d)

CISC

CSC 222: Computer Programming II. Spring 2005

CSC148 Week 2. Larry Zhang

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

Lecture 4 Stack and Queue

Data Abstraction and Specification of ADTs

12 Abstract Data Types

[CS302-Data Structures] Homework 2: Stacks

CS 211 Programming Practicum Fall 2018

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

Binary Tree Application Expression Tree. Revised based on textbook author s notes.

CS 211. Project 5 Infix Expression Evaluation

Syntax-Directed Translation. Lecture 14

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework

The program simply pushes all of the characters of the string into the stack. Then it pops and display until the stack is empty.

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

Postfix (and prefix) notation

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Lecture No.04. Data Structures

BBM 201 DATA STRUCTURES

CSC 222: Computer Programming II. Spring 2004

CSC148H Week 3. Sadia Sharmin. May 24, /20

Chapter 5. ADTs Stack and Queue

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

Data Structure - Stack and Queue-

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Advanced Java Concepts Unit 3: Stacks and Queues

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS THE STACK

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Largest Online Community of VU Students

An Introduction to Trees

Transcription:

Stacks Revised based on textbook author s notes.

Stacks A restricted access container that stores a linear collection. Very common for solving problems in computer science. Provides a last-in first-out (LIFO) protocol.

The Stack New items are added and existing items are removed from the top of the stack.

Why stacks are useful? Many computer science problems (and real life problems) are solved using stacks. We ll touch a few here. Example: determine if a string is a palindrome Here is a list of palindrome http://www.palindromelist.net/ A Toyota s a Toyota. Civic Go dog. Tell a ballet.

We can solve the palindrome problem in recursion

We can also solve the problem using stacks Given a string s, put the sting into a stack, then take the one on stack out in order (LIFO). If the two are the same, it is a palindrome! Original string civic In-stack civic Output civic godog godog godog hello olleh olleh

The Stack ADT A stack stores a linear collection of items with access limited to a last-in first-out order. Adding and removing items is restricted to the top of the stack. Stack() is_empty() len() pop() peek() push( item ) 7

Stack Example # Extracts a collection of integer values from the user # and prints them in reverse order. PROMPT = "Enter an int value (<0 to end): " my_stack = Stack() # Extract the values and push them onto a stack. value = int(input( PROMPT )) while value >= 0 : my_stack.push( value ) value = int(input( PROMPT )) # Pop the values from the stack and print each. while not my_stack.is_empty() : value = my_stack.pop() print( value ) reverse.py

Stack Implementation Several common ways to implement a stack: Python list easiest to implement Linked list better choice when a large number of push and pop operations are performed.

Linked list implementation

Stack Applications Many applications encountered in computer science requires the use of a stack. Balanced delimiters Postfix expressions 11

Balanced Delimiters Many applications use delimiters to group strings of text or simple data into subparts. mathematical expressions programming languages HTML markup 12

Source Code Example Consider the following C++ source code: int sumlist( int thelist[], int size ) { int sum = 0; int i = 0; while( i < size ) { sum += thelist[ i ]; i += 1; } return sum; } 13

Source Code Example The delimiters must be paired and balanced. We can design and implement an algorithm to: scan a C++ source file, and determine if the delimiters are properly paired. 14

Valid C++ Source? from lliststack import Stack def isvalidsource( srcfile ): s = Stack() for line in srcfile : for token in line : if token in "{[(" : s.push( token ) elif token in "}])" : if s.isempty() : return False else : left = s.pop() if (token == "}" and left!= "{") or \ (token == "]" and left!= "[") or \ (token == ")" and left!= "(") : return False return s.isempty()

Mathematical Expressions We work with mathematical expressions on a regular basis. Easy to determine the order of evaluation. Easy to calculate. But the task is more difficult in computer programs. A program cannot visualize the expression to determine the order of evaluation. Must examine one token at a time.

Types of Expressions Three different notations can be used: infix: A + B * C prefix: + A * B C postfix: A B C * +

Infix to Postfix Infix expressions can be easily converted by hand to postfix notation. A * B + C / D 1. Fully parenthesize the expression. ((A * B) + (C / D)) 2. For each set of (), move operator to the end of the closing parenthesis. ((A B *) (C D /) +)

Infix to Postfix (cont) The expression at the end of step 2: ((A B *) (C D /) +) 3. Remove all of the parentheses. A B * C D / + Which results in the postfix version.

Evaluating Postfix Expressions We can evaluate a valid postfix expression using a stack structure. For each token: 1. If the current token is an operand, push its value onto the stack. 2. If the current token is an operator: a. pop the top two operands off the stack. b. perform the operation (top value is RHS operand). c. push the result of the operation back on the stack. The final result will be the last value on the stack.

Postfix Evaluation Examples To illustrate the use of the algorithm, assume the existence of an empty stack, and the following variable assignments A = 8 C = 3 B = 2 D = 4 Evaluate the valid expression: A B C + * D /

Postfix Example #1 Token Alg Step Stack Description ABC+*D/ 1 8 push value of A ABC+*D/ 1 8 2 push value of B ABC+*D/ 1 8 2 3 push value of C ABC+*D/ 2(a) 8 pop top two values: y = 3, x = 2 2(b) 8 compute z = x + y or z = 2 + 3 2(c) 8 5 push result (5) of the addition ABC+*D/ 2(a) pop top two values: y = 5, x = 8 2(b) compute z = x * y or z = 8 * 5 2(c) 40 push result (40) of the multiplication ABC+*D/ 1 40 4 push value of D ABC+*D/ 2(a) pop top two values: y = 4, x = 40 2(b) compute z = x / y or z = 40 / 4 2(c) 10 push result (10) of the division

Postfix Example #2 What happens if the expression is invalid? A B * C D + Token Alg Step Stack Description AB*CD+ 1 8 push value of A AB*CD+ 1 8 2 push value of B AB*CD+ 2(a) pop top two values: y = 2, x = 8 2(b) compute z = x * y or z = 8 * 2 2(c) 16 push result (16) of the multiplication AB*CD+ 1 16 3 push value of C AB*CD+ 1 16 3 4 push value of D AB*CD+ 2(a) 16 pop top two values: y = 4, x = 3 2(b) 16 compute z = x + y or z = 3 + 4 2(c) 16 7 push result (7) of the addition Error xxxxxx xxxxxx Too many values left on the stack.

Postfix Example #3 What happens if there are too many operators for the given number of operands? A B * + C / Token Alg Step Stack Description AB*+C/ 1 8 push value of A AB*+C/ 1 8 2 push value of B AB*+C/ 2(a) pop top two values: y = 2, x = 8 2(b) compute z = x * y or z = 8 * 2 2(c) 16 push result (16) of the multiplication AB*+C/ 2(a) pop top two values: y = 16, x =? Error xxxxxx xxxxxx Only one value on stack, two needed. 24