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

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

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

Assignment 5. Introduction

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

Project 1: Implementation of the Stack ADT and Its Application

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.

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

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

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ).

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

Motivation for Queues

Stacks Fall 2018 Margaret Reid-Miller

A Simple Syntax-Directed Translator

Top of the Stack. Stack ADT

An Introduction to Trees

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

Implementing a Queue with a Linked List

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

Linear Data Structure

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Stacks, Queues (cont d)

Stack and Its Implementation

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Infix to Postfix Conversion

Stacks and their Applications

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto

Stacks Goodrich, Tamassia

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

File Input and Output

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

1. Stack Implementation Using 1D Array

Data Structures and Algorithms

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

Introduction to Programming Using Java (98-388)

CSC 273 Data Structures

The SPL Programming Language Reference Manual

Introduction to Computer Science II (ITI 1121) Midterm Examination

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

CMPT 125: Lecture 3 Data and Expressions

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.

Chapter 4 Defining Classes I

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

CMPS 390 Data Structures

Top of the Stack. Stack ADT

Full file at

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

CPSC 427: Object-Oriented Programming

3. Java - Language Constructs I

Stacks and Queues. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

CS 211 Programming Practicum Fall 2018

Stack Abstract Data Type

Exceptions and Design

1 Lexical Considerations

Lists are great, but. Stacks 2

CS 211 Programming Practicum Spring 2017

Compiling and Running a C Program in Unix

Sprite an animation manipulation language Language Reference Manual

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

LECTURE 17. Expressions and Assignment

What can we do with Coin dispenser?

Lab 7 1 Due Thu., 6 Apr. 2017

Context-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation

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

[CS302-Data Structures] Homework 2: Stacks

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

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CS350: Data Structures Stacks

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

UNIT 3

Operators and Expressions

The PCAT Programming Language Reference Manual

CSE 214 Computer Science II Stack

Postfix (and prefix) notation

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Stacks, Queues and Hierarchical Collections

CS 211 Programming Practicum Spring 2018

Stacks. The unorganized person s data structure. stacks 1

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

CS Introduction to Data Structures How to Parse Arithmetic Expressions

HST 952. Computing for Biomedical Scientists Lecture 8

Stacks. Revised based on textbook author s notes.

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

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

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

Review: Expressions, Variables, Loops, and more.

Stack Abstract Data Type. Section 3.1

8/28/12. Outline. Part 2. Stacks. Linear, time ordered structures. What can we do with Coin dispenser? Stacks

COS 126 General Computer Science Spring Written Exam 1

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

March 13/2003 Jayakanth Srinivasan,

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Transcription:

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions We normally write arithmetic expressions using infix notation: the operator (such as +) goes in between the operands (the two numbers being added). Another way to write arithmetic expressions is to use postfix notation: the two operands come first, and the operator comes after. For example, 3 4 +is same as 3 + 4 1 2-5 - 6 5 / +is same as ((1-2) - 5) + (6 / 5) One advantage of postfix is that you don t need parentheses to indicate the order of evaluation. For instance, (1 + 2) * 3becomes 1 2 + 3 * 1 + (2 * 3)becomes 1 2 3 * +

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 166] Using a Stack to Evaluate Postfix Expressions Pseudocode: while input has more tokens do if the token is an operand then push it on the stack if the token is an operator then pop operand x off the stack pop operand y off the stack apply the operator to x and y push the result back on the stack end while return the value left on the stack This works when all operators are binary (take two operands).

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 167] StringTokenizer Class Java s StringTokenizer class is very helpful to break up the input string into operators and operands called parsing. Create a StringTokenizer objectout of theinput string. It converts the string into a sequence of tokens which are separated by specified delimiters. Use instance method hasmoretokens to test whether there are more tokens. Use instance method nexttoken to get the next token from the input string. Second argument to constructor indicates that, in addition to the whitespace characters (blank, newline, tab, and carriage return), the following are also used as delimiters: +, -, *, and /. Third argument to constructor indicates that all delimiters are to be returned as tokens.

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 168] Java Method to Evaluate Postfix Expressions public static double evalpostfix(string postfix) throws EmptyStackException { Stack S = new Stack(); StringTokenizer parser = new StringTokenizer (postfix, " \n\t\r+-*/", true); while (parser.hasmoretokens()) { String token = parser.nexttoken(); char c = token.charat(0); if (isoperator(c)) { double y = ((Double)S.pop()).doubleValue(); double x = ((Double)S.pop()).doubleValue(); switch (c) { case + : S.push(new Double(x+y)); break; case - : S.push(new Double(x-y)); break; case * : S.push(new Double(x*y)); break; case / : S.push(new Double(x/y)); break; // end switch // end if else if (!iswhitespace(c)) // token is operand S.push(Double.valueOf(token)); // end while return ((Double)S.pop()).doubleValue();

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 169] Evaluating Postfix (cont d) public static boolean isoperator(char c) { return ( (c == + ) (c == - ) (c == * ) (c == / ) ); public static boolean iswhitespace(char c) { return ( (c == ) (c == \n ) (c == \t ) (c == \r ) ); Does not handle negative numbers in the input: it interprets,3 as the binary minus operator, followed by 3, instead of the unary minus applied to 3. Does no error checking to see if operands are wellformed, or if the postfix expression itself is well-formed.

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 170] Implementing a Stack with an Array Since Java suppliesa Stack class, why bother? Basic understanding; other languages. Idea: As elements are pushed, they are stored sequentially in an array, keeping track of the last element entered. To pop, return the element at the end of the active part of the array. Issues for Java implementation: elements in the array are to be of type Object throw exception if try to pop an empty stack dynamically increase the size of the array to avoid overflow To handle the last point, we ll do the following: initially, the size of the array is, say, 16. if array is full and a push occurs, use new to create an array twice the size of current array, and copy everything in old array to new array.

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 171] Implementing a Stack with an Array in Java class Stack { private Object[] A; private int next; public Stack () { A = new Object[16]; next = 0; public void push(object obj) { if (next == A.length) { // array is full, double its size Object[] newa = new Object[2*A.length]; for (int i = 0; i < next; i++) // copy newa[i] = A[i]; A = newa; // old A can now be garbage collected A[next] = obj; next++; public Object pop() throws EmptyStackException { if (next == 0) throw new EmptyStackException(); else { next--; return A[next];

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 172] Implementing a Stack with an Array in Java (cont d) public boolean empty() { return (next == 0); public Object peek() throws EmptyStackException { if (next == 0) throw new EmptyStackException(); else return A[next-1]; // end Stack class class EmptyStackException extends Exception { public EmptyStackException() { super();

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 173] Time Performance of Array Implementation push: O(1) UNLESS array is full; then it is O(n) plus time for system to allocate space (more later) pop: O(1) empty: O(1) peek: O(1)

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 174] Impementing a Stack with a Linked List in Java Idea: a push causes a new node to be inserted at the beginning of the list, and a pop causes the first node of the list to be removed and returned. class StackNode { Object item; StackNode link; class Stack { private StackNode top; // first node in list, the top public Stack () { top = null; public void push(object obj) { StackNode node = new StackNode(); node.item = obj; node.link = top; top = node;

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 175] Implementing a Stack with a Linked List in Java (cont d) public Object pop() throws EmptyStackException { if (top == null) throw new EmptyStackException(); else { StackNode temp = top; top = top.link; return temp.item; public boolean empty() { return (top == null); public Object peek() throws EmptyStackException { if (top == null) throw new EmptyStackException(); else return top.item;

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 176] Time Performance of Linked List Implementation push: O(1) plus time for system to allocate space (more later) pop: O(1) empty: O(1) peek: O(1)

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 177] Interchangeability of Implementations If you have done things right, you can: write a program using the built-in Stack class compile and run that program then make available your own Stack class, using the array implementation (e.g., put Stack.class in the same directory WITHOUT CHANGING OR RECOMPILING YOUR PROGRAM, run your program it will use the local Stack implementation and will still be correct! then replace the array-based Stack.class file with your own linked-list-based Stack.class file again, WITHOUT CHANGING OR RECOMPIL- ING YOUR PROGRAM, run your program it will use the local Stack implementation and will still be correct!