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

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

Stack and Its Implementation

CSC 273 Data Structures

The Stack and Queue Types

STACKS AND QUEUES. Problem Solving with Computers-II

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

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

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

Stacks Fall 2018 Margaret Reid-Miller

CSIS 10B Lab 2 Bags and Stacks

Stacks. Revised based on textbook author s notes.

Top of the Stack. Stack ADT

Stacks and their Applications

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

CS 211 Programming Practicum Spring 2017

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

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

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

Stack Abstract Data Type

March 13/2003 Jayakanth Srinivasan,

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

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

Infix to Postfix Conversion

Lab 7 1 Due Thu., 6 Apr. 2017

Linear Data Structure

Top of the Stack. Stack ADT

Introduction to Programming Using Java (98-388)

CS 211 Programming Practicum Spring 2018

Stacks, Queues (cont d)

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

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

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.

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

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

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

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

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

CS 211 Programming Practicum Fall 2018

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

[CS302-Data Structures] Homework 2: Stacks

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

Advanced Java Concepts Unit 3: Stacks and Queues

Project 1: Implementation of the Stack ADT and Its Application

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

Lecture 4 Stack and Queue

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

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

CMPS 390 Data Structures

Introduction to Computer Science II (ITI 1121) Midterm Examination

Lecture Data Structure Stack

Problem with Scanning an Infix Expression

CS W3134: Data Structures in Java

Data Structures Week #3. Stacks

Java Primer 1: Types, Classes and Operators

BBM 201 DATA STRUCTURES

List, Stack, and Queues

Lecture 12 ADTs and Stacks

Data Structure - Stack and Queue-

Basic Data Structures

infix expressions (review)

Lists are great, but. Stacks 2

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

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

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

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

1. Stack Implementation Using 1D Array

Basic Data Structures 1 / 24

CS350: Data Structures Stacks

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

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

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

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

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

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

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

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

BBM 201 DATA STRUCTURES

An Introduction to Trees

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

CS 106B Lecture 5: Stacks and Queues

CSC Java Programming, Fall Java Data Types and Control Constructs

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

CS 206 Introduction to Computer Science II

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

Ch. 18: ADTs: Stacks and Queues. Abstract Data Type

Stacks and Queues. Chapter Stacks

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Data Structure. Recitation IV

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

PA3 Design Specification

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

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

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

Programming Abstractions

CSC 222: Computer Programming II. Spring 2005

DATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.

Discussion of project # 1 permutations

Transcription:

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 Delimiters in an Infix Algebraic Expression A Problem Solved: Transforming an Infix Expression to a Postfix Expression A Problem Solved: Evaluating Postfix Expressions A Problem Solved: Evaluating Infix Expressions Copyright 2012 by Pearson Education, Inc. All rights reserved

Contents The Program Stack Java Class Library: The Class Stack Copyright 2012 by Pearson Education, Inc. All rights reserved

Objectives Describe operations of ADT stack Use stack to decide whether delimiters in an algebraic expression are paired correctly Use stack to convert infix expression to postfix expression Copyright 2012 by Pearson Education, Inc. All rights reserved

Objectives Use stack to evaluate postfix expression Use stack to evaluate infix expression Use a stack in a program Describe how Java run-time environment uses stack to track execution of methods Copyright 2012 by Pearson Education, Inc. All rights reserved

Specifications of a Stack Organizes entries according to order added All additions added to one end of stack Added to top Called a push Access to stack restricted Access only top entry Remove called a pop Copyright 2012 by Pearson Education, Inc. All rights reserved

Figure 5-1 Some familiar stacks Copyright 2012 by Pearson Education, Inc. All rights reserved

public interface StackInterface < T > { /** Adds a new entry to the top of this stack. @param newentry an object to be added to the stack */ public void push (T newentry); /** Removes and returns this stacks top entry. @return either the object at the top of the stack or, if the stack is empty before the operation, null */ public T pop (); /** Retrieves this stacks top entry. @return either the object at the top of the stack or null if the stack is empty */ public T peek (); /** Detects whether this stack is empty. @return true if the stack is empty */ public boolean isempty (); /** Removes all entries from this stack */ public void clear (); } // end StackInterface Stack Interface Copyright 2012 by Pearson Education, Inc. All rights reserved

What is an Interface? Like a class, except none of the methods defined Only signatures showing what they take/return Uses keyword interface rather than class Like a Contract If a class satisfies methods in StackInterface it can be used interchangeably with any other class that satisfies method in StackInterface Allows multiple implementations for a given ADT, Copyright 2012 by Pearson Education, Inc. All rights reserved

BlueJ showing StackInterface and 2 classes that implement it Copyright 2012 by Pearson Education, Inc. All rights reserved

Stack Implementation 1)-- ArrayStack For an ArrayStack, we choose to represent data using an internal array Copyright 2012 by Pearson Education, Inc. All rights reserved

Stack Implementation 2)-- LinkedStack For a LinkedStack we choose to represent data using a linked chain of nodes: Both approaches have pros and cons Copyright 2012 by Pearson Education, Inc. All rights reserved

Interfaces allow flexibility If both ArrayStack and LinkedStack implement StackInterface, we can use either one in a program that calls for stacks. Depending on our app, one or the other might perform better. Regardless of which we use, all stack code except instantiation is same Copyright 2012 by Pearson Education, Inc. All rights reserved

Using Class Stack Example usage Copyright 2012 by Pearson Education, Inc. All rights reserved

Figure 5-2 A stack of strings after (a) push adds Jim; (b) push adds Jess; (c) push adds Jill; (d) push adds Jane; (e) push adds Joe; (f ) pop retrieves and removes Joe; (g) pop retrieves and removes Jane Copyright 2012 by Pearson Education, Inc. All rights reserved

Do Lab 2B Problems 1 & 2 Now

Need for Wrapper classes Bag or a Stack, List or Queue all use an internal array of Object references. We can make Bags or Stacks of String, Item, Name, Student, etc.

Need for Wrapper classes (2) But primitive collections are not allowed: Bag<double> Stack<char> To get around this, Java provides Wrapper classes Double, Integer, Boolean, Character, etc These classes wrap primitive values in an object Provide "autoboxing" and "auto-unboxing" to make them mostly the same as working with primitives

Static Methods in Wrapper Classes The Wrapper classes provide a wide variety of "utility" methods for working with associated primitive counterparts. Suppose we have char symbol = 'x'; Character class has methods to tell if a char is a alphabetical letter digit Character.isAlpha( symbol) Character.isDigit(symbol) Integer class has methods to convert String to int Integer.parseInt("125"); Copyright 2012 by Pearson Education, Inc. All rights reserved Integer.parseInt("hello");

Demo this in lab now, Problems 3 and 4 Copyright 2012 by Pearson Education, Inc. All rights reserved

Application of Stacks Consider the arithmetic statement in the assignment statement: x = a * b + c Compiler must generate machine instructions 1. LOAD a 2. MULT b 3. ADD c 4. STORE x Note: this is "infix" notation The operators are between the operands Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 24

RPN or Postfix Notation Most compilers convert an expression in infix notation to postfix the operators are written after the operands So a * b + c becomes a b * c + Advantage: expressions can be written without parentheses Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 25

Postfix and Prefix Examples INFIX RPN (POSTFIX) PREFIX A + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D A B + A B * C + A B C + * A B C D--- A B-C-D- + A B + * A B C * A + B C -A-B-C D ---A B C D Prefix : Operators come before the operands Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 26

Evaluating RPN Expressions "By hand" (Underlining technique): 1. Scan the expression from left to right to find an operator. 2. Locate ("underline") the last two preceding operands and combine them using this operator. 3. Repeat until the end of the expression is reached. Example: 2 3 4 + 5 6 - - * 2 3 4 + 5 6 - - * 2 7 5 6 - - * 2 7 5 6 - - * 2 7-1 - * 2 7-1 - * 2 8 * 2 8 * Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 16 27

Evaluating RPN Expressions By using a stack algorithm 1. Initialize an empty stack 2. Repeat the following until the end of the expression is encountered a) Get the next token (const, var, operator) in the expression b) Operand push onto stack Operator do the following i. Pop 2 values from stack ii. Apply operator to the two values iii. Push resulting value back onto stack Note: if only 1 value on stack, this is an invalid RPN expression 3. When end of expression encountered, value of expression is the (only) number left in stack Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 28

Evaluation of Postfix Note the changing status of the stack Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 29

Infix RPN Conversion Method By hand: "Fully parenthesize-move-erase" method: 1. Fully parenthesize the expression. 2. Replace each right parenthesis by the corresponding operator. 3. Erase all left parentheses. Examples: A * B + C ((A * B) + C) A * (B + C) (A * (B + C) ) ((A B * C + (A (B C + * A B * C + A B C + * Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 32

Infix RPN Stack Algorithm 1. Initialize an empty stack of operators 2. While no error &&!end of expression a) Get next input "token" from infix expression b) If token is i. "(" : push onto stack const, var, arith operator, left or right paren ii. ")" : pop and display stack elements until "(" occurs, do not display it Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 33

Stack Algorithm iii. operator if operator has higher priority than top of stack push token onto stack else pop and display top of stack repeat comparison of token with top of stack iv. operand display it Note: Left parenthesis in stack has lower priority than operators 3. When end of infix reached, pop and display stack items until empty Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 34

Copyright 2012 by Pearson Education, Inc. All rights reserved

Copyright 2012 by Pearson Education, Inc. All rights reserved

Stack Algorithm 1. Initialize an empty stack of operators 2. While no error &&!end of expression a) Get next input "token" from infix expression b) If token is i. "(" : push onto stack const, var, arith operator, left or right paren ii. ")" : pop and display stack elements until "(" occurs, do not display it Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 37

Stack Algorithm iii. operator if operator has higher priority than top of stack push token onto stack else pop and display top of stack repeat comparison of token with top of stack iv. operand display it Note: Left parenthesis in stack has lower priority than operators 3. When end of infix reached, pop and display stack items until empty Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 38

The Program (Runtime) Stack FIGURE 5-13 The program stack at three points in time: (a) when main begins execution; (PC is the program counter)

The Program Stack FIGURE 5-13 The program stack at three points in time: (b) when methoda begins execution; (PC is the program counter) Copyright 2012 by Pearson Education, Inc. All rights reserved

The Program Stack FIGURE 5-13 The program stack at three points in time: (c) when methodb begins execution; (PC is the program counter) Copyright 2012 by Pearson Education, Inc. All rights reserved

Java Class Library: The Class Stack Has a single constructor Creates an empty stack Remaining methods differences from our StackInterface are highlighted public T push(t item); public T pop(); public T peek(); public boolean empty(); Copyright 2012 by Pearson Education, Inc. All rights reserved

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