Stack Abstract Data Type. Section 3.1

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

Stack Abstract Data Type

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

Stacks Fall 2018 Margaret Reid-Miller

CSC 273 Data Structures

CSC 222: Computer Programming II. Spring 2005

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

Stacks. The unorganized person s data structure. stacks 1

CMPS 390 Data Structures

Stack and Its Implementation

CS 211 Programming Practicum Spring 2017

CS 211 Programming Practicum Spring 2018

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

Stack Applications. parsing a postfix expression evaluating postfix expressions. converting infix sums from infix to postfix

1. Stack Implementation Using 1D Array

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

Stacks. Revised based on textbook author s notes.

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

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

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

CS 211 Programming Practicum Fall 2018

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

CSE 214 Computer Science II Stack

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

Top of the Stack. Stack ADT

CS350: Data Structures Stacks

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.

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

Project 1: Implementation of the Stack ADT and Its Application

Stacks and Queues. Chapter Stacks

Data Structures and Algorithms

Queues Fall 2018 Margaret Reid-Miller

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

infix expressions (review)

Top of the Stack. Stack ADT

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

March 13/2003 Jayakanth Srinivasan,

CIS Fall Data Structures Midterm exam 10/16/2012

Lecture 12 ADTs and Stacks

Data Structures and Algorithms

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

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

Postfix (and prefix) notation

Assignment 5. Introduction

CSC 321: Data Structures. Fall 2012

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

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

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

CS 211. Project 5 Infix Expression Evaluation

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

File Input and Output

3. Java - Language Constructs I

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

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

STACKS AND QUEUES. Problem Solving with Computers-II

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

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

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

Stacks, Queues (cont d)

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Stacks and Queues. David Greenstein Monta Vista

[CS302-Data Structures] Homework 2: Stacks

CIS265 Homework7 A (partial) solution showing creation/traversal of an expression-tree made from a a valid arithmetical expression

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

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.

An Introduction to Trees

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

The Stack and Queue Types

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

C27a: Stack and Queue

CSE 143 SAMPLE MIDTERM

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

Building Java Programs

CSC 222: Computer Programming II. Spring 2004

Lists are great, but. Stacks 2

Stacks II. Adventures in Notation. stacks2 1

csci 210: Data Structures Stacks and Queues

Stacks Goodrich, Tamassia

Stacks Goodrich, Tamassia Stacks

1 Lexical Considerations

Linear Data Structure

CS 307 Final Fall 2009

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

Programming with Java

H212 Introduction to Software Systems Honors

Advanced Java Concepts Unit 3: Stacks and Queues

Stacks and their Applications

Data Structures Week #3. Stacks

BBM 201 DATA STRUCTURES

CSC 321: Data Structures. Fall 2013

Introduction to Programming Using Java (98-388)

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

Lab 7 1 Due Thu., 6 Apr. 2017

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

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Full file at

Implementing Dynamic Data Structures

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

Data Structure. Recitation IV

Loops and Expression Types

Transcription:

CHAPTER 3 Stacks

Chapter Objectives To learn about the stack data type and how to use its four methods: push pop peek empty To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list To see how to use a stack to perform various applications, including finding palindromes, testing for balanced (properly nested) parentheses, and evaluating arithmetic expressions

Stack Abstract Data Type Section 3.1

Stack Abstract Data Type A stack is one of the most commonly used data structures in computer science A stack can be compared to a Pez dispenser Only the top item can be accessed You can extract only one item at a time The top element in the stack is the last added to the stack (most recently) The stack s storage policy is Last-In, First- Out, or LIFO

Specification of the Stack Abstract Data Type Only the top element of a stack is visible; therefore the number of operations performed by a stack are few We need the ability to test for an empty stack (empty) inspect the top element (peek) retrieve the top element (pop) put a new element on the stack (push)

Specification of the Stack Abstract Data Type (cont.) 6 Listing 3.1 (StackInt.java, page 151) public interface StackInt<E> { E push(e obj); E peek(); E pop(); boolean empty();

A Stack of Strings Rich is the oldest element on the stack and Jonathan is the youngest (Figure a) String last = names.peek(); stores a reference to Jonathan in last String temp = names.pop(); removes Jonathan and stores a reference to it in temp (Figure b) names.push( Philip ); pushes Philip onto the stack (Figure c)

Stack Applications Section 3.2

Finding Palindromes Palindrome: a string that reads identically in either direction, letter by letter (ignoring case) kayak "I saw I was I" Able was I ere I saw Elba "Level madam level" Problem: Write a program that reads a string and determines whether it is a palindrome

Finding Palindromes (cont.)

Finding Palindromes (cont.) import java.util.*; public class PalindromeFinder { private String inputstring; private Stack<Character> charstack = new Stack<Character>(); public PalindromeFinder(String str) {... inputstring = str; fillstack(); // fills the stack with the characters in inputstring

Finding Palindromes (cont.) Solving using a stack: Push each string character, from left to right, onto a stack ka y kay k a y a k ka y ka k private void fillstack() { for(int i = 0; i < inputstring.length(); i++) { charstack.push(inputstring.charat(i));

Finding Palindromes (cont.) Solving using a stack: Pop each character off the stack, appending each to the StringBuilder result kaykayka k ya ka y k a y a k ka k private String buildreverse(){ StringBuilder result = new StringBuilder(); while(!charstack.empty()) { result.append(charstack.pop()); return result.tostring();

Finding Palindromes (cont.)... public boolean ispalindrome() { return inputstring.equalsignorecase(buildreverse());

Finding Palindromes (cont.) 15 Listing 3.2 (PalindromeFinder.java, page155) package KW.CH03; import java.util.stack; public class PalindromeFinder { private String inputstring; private Stack<Character> charstack = new Stack<Character>(); public PalindromeFinder(String str) { inputstring = str; fillstack(); private void fillstack() { for (int i = 0; i < inputstring.length(); i++) { charstack.push(inputstring.charat(i)); private String buildreverse() { StringBuilder result = new StringBuilder(); while (!charstack.empty()) { result.append(charstack.pop()); return result.tostring(); public boolean ispalindrome() { return inputstring.equalsignorecase(buildreverse());

Testing To test this class using the following inputs: a single character (always a palindrome) multiple characters in a word multiple words different cases even-length strings odd-length strings the empty string (considered a palindrome)

Balanced Parentheses When analyzing arithmetic expressions, it is important to determine whether an expression is balanced with respect to parentheses ( a + b * ( c / ( d e ) ) ) + ( d / e ) The problem is further complicated if braces or brackets are used in conjunction with parentheses The solution is to use stacks!

Balanced Parentheses (cont.)

Balanced Parentheses (cont.)

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) ( ( 0 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 0

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) ( ( 0 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 1

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) ( ( 0 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 2

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) 0 1 2 3 4 5 6 7 8 9 10 [( ( ( w * [ x + y ] / z ) balanced : true index : 3

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) [ ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 4

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) [ ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 5

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) [ ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 6

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) [( ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) Matches! Balanced still true balanced : true index : 7

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 8

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) balanced : true index : 9

Balanced Parentheses (cont.) Expression: (w * [x + y] / z) ( 0 ( 1 2 3 4 5 6 7 8 9 10 w * [ x + y ] / z ) Matches! Balanced still true balanced : true index : 10

Testing Provide a variety of input expressions displaying the result true or false Try several levels of nested parentheses Try nested parentheses where corresponding parentheses are not of the same type Try unbalanced parentheses No parentheses at all! PITFALL: attempting to pop an empty stack will throw an EmptyStackException. You can guard against this by either testing for an empty stack or catching the exception

Testing (cont.) 32 Listing 3.3 (ParenChecker.java, pages 159-160) package KW.CH03; import java.util.stack; import java.util.emptystackexception; import javax.swing.joptionpane; public class ParenChecker { private static final String OPEN = "([{"; private static final String CLOSE = ")]"; public static boolean isbalanced(string expression) { Stack<Character> s = new Stack<Character>(); boolean balanced = true; try { int index = 0; while (balanced && index < expression.length()) { char nextch = expression.charat(index); if (isopen(nextch)) { s.push(nextch); else if (isclose(nextch)) { char topch = s.pop(); balanced = OPEN.indexOf(topCh) == CLOSE.indexOf(nextCh); index++; catch (EmptyStackException ex) { balanced = false; return (balanced && s.empty());

Testing (cont.) 33 Listing 3.3 (ParenChecker.java, pages 159-160) private static boolean isopen(char ch) { return OPEN.indexOf(ch) > -1; private static boolean isclose(char ch) { return CLOSE.indexOf(ch) > -1; public static void main(string args[]) { String expression = JOptionPane.showInputDialog( "Enter an expression containing parentheses"); if (ParenChecker.isBalanced(expression)) { JOptionPane.showMessageDialog(null, expression + " is balanced"); else { JOptionPane.showMessageDialog(null, expression + " is not balanced"); System.exit(0);

Implementing a Stack Section 3.3 Data Structure Implementation 1. Java API : Stack Collection (From Vector Collection) 2. Adapter Class : Stack ß ArrayList, LinkedList, Vector (Collection) 3. Low Level : Array, Linked List(Node)

Implementing a Stack as an Extension of Vector The Java API includes a Stack class as part of the package java.util : public class Stack<E> extends Vector<E> The Vector class implements a growable array of objects Elements of a Vector can be accessed using an integer index and the size can grow or shrink as needed to accommodate the insertion and removal of elements

Implementing a Stack as an Extension of Vector (cont.) We can use Vector's add method to implement push: public E push(obj E) { add(obj); return obj; pop can be coded as public E pop throws EmptyStackException { try { return remove (size() 1); catch (ArrayIndexOutOfBoundsException ex) { throw new EmptyStackException();

Implementing a Stack as an Extension of Vector (cont.) Because a Stack is a Vector, all of Vector operations can be applied to a Stack (such as searches and access by index) But, since only the top element of a stack should be accessible, this violates the principle of information hiding

Implementing a Stack with a List Component As an alternative to a stack as an extension of Vector, we can write a class, ListStack, that has a List component (in the example below, thedata) We can use either the ArrayList, Vector, or the LinkedList classes, as all implement the List interface. The push method, for example, can be coded as public E push(e obj) { thedata.add(obj); return obj; A class which adapts methods of another class by giving different names to essentially the same methods (push instead of add) is called an adapter class Writing methods in this way is called method delegation

39 Implementing a Stack with a List Component (cont.) Listing 3.4 (ListStack.java, pages 164-165) package KW.CH03; import java.util.emptystackexception; public class LinkedStack<E> implements StackInt<E> { private static class Node<E> { private E data; private Node<E> next; private Node(E dataitem) { data = dataitem; next = null; private Node(E dataitem, Node<E> noderef) { data = dataitem; next = noderef;

40 Implementing a Stack with a List Component (cont.) Listing 3.4 (ListStack.java, pages 164-165) private Node<E> topofstackref = null; public E push(e obj) { topofstackref = new Node<E>(obj, topofstackref); return obj; public E pop() { if (empty()) { throw new EmptyStackException(); else { E result = topofstackref.data; topofstackref = topofstackref.next; return result; public E peek() { if (empty()) { throw new EmptyStackException(); else { return topofstackref.data;

41 Implementing a Stack with a List Component (cont.) Listing 3.4 (ListStack.java, pages 164-165) public boolean empty() { return topofstackref == null; public int size() { /** Exercise */ int count = 0; Node<E> current = topofstackref; while (current!= null) { count++; current = current.next; return count;

Implementing a Stack Using an Array If we implement a stack as an array, we would need... capacity public class ArrayStack<E> implements StackInt<E> { @SupressWarnings("unchecked") public ArrayStack() { thedata = (E[])new Object[INITIAL_CAPACITY]; There is no size variable or method Allocate storage for an array with a default private E[] thedata; Keep track of the top of the stack (subscript of the element int topofstack = -1; at the top of the stack; for private static final int INITIAL_CAPACITY empty = 10; stack = -1)

Implementing a Stack Using an Array (cont.) ArrayStack thedata = topofstack = -1 30 12 public E push(e obj) { if (topofstack == thedata.length - 1){ reallocate(); topofstack++; thedata[topofstack] = obj; return obj; Object[] [0] = null [1] = null [2] = null [3] = null [4] = null [5] = null [6] = null [7] = null [8] = null [9] = null Character value = 'J' Character value = 'a' Character value = 'v' Character value = 'a'

Implementing a Stack Using an Array (cont.) @Override public E pop() { if (empty()) { throw new EmptyStackException(); return thedata[topofstack--];

Implementing a Stack Using an Array (cont.) This implementation is O(1), in contrast to the Pez analogy and the kayak example, which are both O(n)

Implementing a Stack as a Linked Data Structure We can also implement a stack using a linked list of nodes push inserts a node at the when It is easiest the list to is empty, insert and pop head and pop deletes the delete from returns the head null of a list node at the head

47 Implementing a Stack as a Linked Data Structure (cont.) Listing 3.5 (LinkedStack.java, pages 168-169) package KW.CH03; import java.util.emptystackexception; public class LinkedStack<E> implements StackInt<E> { private static class Node<E> { private E data; private Node<E> next; private Node(E dataitem) { data = dataitem; next = null; private Node(E dataitem, Node<E> noderef) { data = dataitem; next = noderef; private Node<E> topofstackref = null; public E push(e obj) { topofstackref = new Node<E>(obj, topofstackref); return obj;

48 Implementing a Stack as a Linked Data Structure (cont.) Listing 3.5 (LinkedStack.java, pages 168-169) public E pop() { if (empty()) { throw new EmptyStackException(); else { E result = topofstackref.data; topofstackref = topofstackref.next; return result; public E peek() { if (empty()) { throw new EmptyStackException(); else { return topofstackref.data; public boolean empty() { return topofstackref == null; public int size() {/*</exercise>*/ int count = 0; Node<E> current = topofstackref; while (current!= null) { count++; current = current.next; return count;

Comparison of Stack Implementations Extending a Vector (as is done by Java) is a poor choice for stack implementation, since all Vector methods are accessible The easiest implementation uses a List component (ArrayList is the simplest) for storing data An underlying array requires reallocation of space when the array becomes full, and an underlying linked data structure requires allocating storage for links As all insertions and deletions occur at one end, they are constant time, O(1), regardless of the type of implementation used

Additional Stack Applications Section 3.4

Additional Stack Applications Postfix and infix notation Expressions normally are written in infix form, but it easier to evaluate an expression in postfix form since there is no need to group sub-expressions in parentheses or worry about operator precedence

Evaluating Postfix Expressions Write a class that evaluates a postfix expression Use the space character as a delimiter between tokens

Evaluating Postfix Expressions (cont.) 4 4 7 * 20-1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 47 4 4 7 * 20-1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 7 4 * 7 4 7 * 20-4 1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 28 28 4 7 * 20-1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 20 28 28 4 7 * 20-1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 20 28-20 4 7 * 20-28 1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 8 8 4 7 * 20-1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 8 4 7 * 20-1. create an empty stack of integers 2. while there are more tokens 3. get the next token 4. if the first character of the token is a digit 5. push the token on the stack 6. else if the token is an operator 7. pop the right operand off the stack 8. pop the left operand off the stack 9. evaluate the operation 10. push the result onto the stack 11. pop the stack and return the result

Evaluating Postfix Expressions (cont.) 61 Listing 3.6 (PostfixEvaluator.java, pages 173-175) package KW.CH03; import java.util.stack; import java.util.scanner; import java.util.emptystackexception; public class PostfixEvaluator { public static class SyntaxErrorException extends Exception { SyntaxErrorException(String message) { super(message); private Stack<Integer> operandstack; private int evalop(char op) { int rhs = operandstack.pop(); int lhs = operandstack.pop(); int result = 0; switch (op) { case '+': result = lhs + rhs; break; case '-': result = lhs - rhs; break; case '/': result = lhs / rhs; break; case '*': result = lhs * rhs; break; return result;

Evaluating Postfix Expressions (cont.) 62 Listing 3.6 (PostfixEvaluator.java, pages 173-175) private boolean isoperator(char ch) { return OPERATORS.indexOf(ch)!= -1; public int eval(string expression) throws SyntaxErrorException { operandstack = new Stack<Integer>(); Scanner scan = new Scanner(expression); try { String nexttoken; while ((nexttoken = scan.findinline("\\d+ [-+/\\*]"))!= null) { int value = Integer.parseInt(nextToken); operandstack.push(value); // Is it an operator? else if (isoperator(nexttoken.charat(0))) { int result = evalop(nexttoken.charat(0)); operandstack.push(result); else { throw new SyntaxErrorException("Invalid character encountered"); // End while. int answer = operandstack.pop(); // Operand stack should be empty. if (operandstack.empty()) { return answer; else { throw new SyntaxErrorException( "Syntax Error: Stack should be empty"); catch (EmptyStackException ex) { throw new SyntaxErrorException( "Syntax Error: The stack is empty");

Evaluating Postfix Expressions (cont.) Testing: write a driver which creates a PostfixEvaluator object reads one or more expressions and report the result catches PostfixEvaluator.SyntaxErrorException exercises each path by using each operator exercises each path through the method by trying different orderings and multiple occurrences of operators tests for syntax errors: n an operator without any operands n a single operand n an extra operand n an extra operator n a variable name n the empty string

Converting from Infix to Postfix Convert infix expressions to postfix expressions Assume: expressions consists of only spaces, operands, and operators space is a delimiter character all operands that are identifiers begin with a letter or underscore all operands that are numbers begin with a digit

Converting from Infix to Postfix (cont.) 65 Example: convert w 5.1 / sum * 2 to its postfix form w 5.1 sum / 2 * -

Converting from Infix to Postfix (cont.)

Converting from Infix to Postfix (cont.)

Converting from Infix to Postfix (cont.)

Converting from Infix to Postfix (cont.)

Converting from Infix to Postfix (cont.) 70 Listing 3.7 (InfixToPostfix.java, pages 181-183) package KW.CH03; import java.util.stack; import java.util.emptystackexception; import java.util.regex.pattern; import java.util.scanner; public class InfixToPostfix { public static class SyntaxErrorException extends Exception { SyntaxErrorException(String message) { super(message); private Stack<Character> operatorstack; private static final String OPERATORS = "-+*/"; private static final int[] PRECEDENCE = {1, 1, 2, 2; private static final Pattern tokens = Pattern.compile("\\d+\\.\\d* \\d+ " + "\\p{javajavaidentifierstart\\p{javajavaidentifierpart*" + " [" + OPERATORS + "]"); private StringBuilder postfix;

Converting from Infix to Postfix (cont.) 71 Listing 3.7 (InfixToPostfix.java, pages 181-183) public String convert(string infix) throws SyntaxErrorException { operatorstack = new Stack<Character>(); postfix = new StringBuilder(); Scanner s = new Scanner(infix); try { String nexttoken = null; while ((nexttoken = s.findinline(tokens))!= null) { char firstchar = nexttoken.charat(0); if (Character.isJavaIdentifierStart(firstChar) Character.isDigit(firstChar)) { postfix.append(nexttoken); postfix.append(' '); // Is it an operator? else if (isoperator(firstchar)) { processoperator(firstchar); else { throw new SyntaxErrorException ("Unexpected Character Encountered: " + firstchar); // End while. while (!operatorstack.empty()) { char op = operatorstack.pop(); postfix.append(op); postfix.append(' '); return postfix.tostring(); catch (EmptyStackException ex) { throw new SyntaxErrorException("Syntax Error: The stack is empty");

Converting from Infix to Postfix (cont.) 72 Listing 3.7 (InfixToPostfix.java, pages 181-183) private void processoperator(char op) { if (operatorstack.empty()) { operatorstack.push(op); else { char topop = operatorstack.peek(); if (precedence(op) > precedence( topop)) { operatorstack.push(op); else { while (!operatorstack.empty()&& precedence(op) <= precedence( topop)) { operatorstack.pop(); postfix.append(topop); postfix.append(' '); if (!operatorstack.empty()) { topop = operatorstack.peek(); operatorstack.push(op); private boolean isoperator(char ch) { return OPERATORS.indexOf(ch)!= -1; private int precedence(char op) { return PRECEDENCE[OPERATORS.indexOf(op)];

Converting from Infix to Postfix (cont.) Testing Use enough test expressions to satisfy yourself that the conversions are correct for properly formed input expressions Use a driver to catch InfixToPostfix.SyntaxErrorException Listing 3.8 (TestInfixToPostfix.java, page 184)

Converting from Infix to Postfix (cont.) Listing 3.8 (TestInfixToPostfix.java, page 184) package KW.CH03; import java.util.scanner; public class TestInfixToPostfix { public static void main(string[] args) { InfixToPostfix evaluator = new InfixToPostfix(); String line; Scanner in = new Scanner(System.in); do { System.out.println("Enter an infix expression to evaluate"); if (in.hasnextline()) { line = in.nextline(); try { String result = evaluator.convert(line); System.out.println("Value is " + result); catch (InfixToPostfix.SyntaxErrorException ex) { System.out.println("Syntax error " + ex.getmessage()); else { break; while (true);

Converting Expressions with Parentheses The ability to convert expressions with parentheses is an important (and necessary) addition Modify processoperator to push each opening parenthesis onto the stack as soon as it is scanned When a closing parenthesis is encountered, pop off operators until the opening parenthesis is encountered Listing 3.9 (InfixToPostfixParens.java, pages 186-188)

Converting Expressions with Parentheses Listing 3.9 (InfixToPostfixParens.java, pages 186-188) package KW.CH03; import java.util.stack; import java.util.emptystackexception; import java.util.regex.pattern; import java.util.scanner; public class InfixToPostfixParens { public static class SyntaxErrorException extends Exception { SyntaxErrorException(String message) { super(message); private Stack<Character> operatorstack; private static final String OPERATORS = "-+*/()"; private static final Pattern pattern = Pattern.compile("\\d+\\.\\d* \\d+ " + "\\p{javajavaidentifierstart\\p{javajavaidentifierpart*" + " [" + OPERATORS + "]"); private static final int[] PRECEDENCE = {1, 1, 2, 2, -1, -1; private StringBuilder postfix;

Converting Expressions with Parentheses Listing 3.9 (InfixToPostfixParens.java, pages 186-188) String convert(string infix) throws SyntaxErrorException { operatorstack = new Stack<Character>(); postfix = new StringBuilder(); Scanner scan = new Scanner(infix); try { String nexttoken; while ((nexttoken = scan.findinline(pattern))!= null) { char firstchar = nexttoken.charat(0); if (Character.isJavaIdentifierStart(firstChar) Character.isDigit(firstChar)) { postfix.append(nexttoken); postfix.append(' '); // Is it an operator? else if (isoperator(firstchar)) { processoperator(firstchar); else { throw new SyntaxErrorException("Unexpected Character Encountered: " + firstchar); // End while. while (!operatorstack.empty()) { char op = operatorstack.pop(); if (op == '(') { throw new SyntaxErrorException("Unmatched opening parenthesis"); postfix.append(op); postfix.append(' '); return postfix.tostring();

Converting Expressions with Parentheses Listing 3.9 (InfixToPostfixParens.java, pages 186-188) catch (EmptyStackException ex) { throw new SyntaxErrorException("Syntax Error: The stack is empty"); private void processoperator(char op) { if (operatorstack.empty() op == '(') { operatorstack.push(op); else { char topop = operatorstack.peek(); if (precedence(op) > precedence( topop)) { operatorstack.push(op); else { while (!operatorstack.empty()&& precedence(op) <= precedence( topop)) { operatorstack.pop(); if (topop == '(') { break; postfix.append(topop); postfix.append(' '); if (!operatorstack.empty()) { topop = operatorstack.peek(); if (op!= ')') { operatorstack.push(op);

Converting Expressions with Parentheses Listing 3.9 (InfixToPostfixParens.java, pages 186-188) private boolean isoperator(char ch) { return OPERATORS.indexOf(ch)!= -1; private int precedence(char op) { return PRECEDENCE[OPERATORS.indexOf(op)];