Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 14 Stacks.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 14 Stacks."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 14 Stacks Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Collection A stack is a list of items that are accessible at only one end of the sequence, called the top of the stack. A stack is a list of items that are accessible at only one end of the sequence, called the top of the stack. A pile of items placed one on top of the other is a model of a stack. A pile of items placed one on top of the other is a model of a stack.

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Collection (continued)

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Operations Stack operations are restricted to the element at the top of the stack. push(item) adds item at the top pop() removes element from the top peek() accesses value at the top Stack operations are restricted to the element at the top of the stack. push(item) adds item at the top pop() removes element from the top peek() accesses value at the top

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Operations (continued) An item removed (pop) from the stack is the last element that was added (push) to the stack. A stack has LIFO (last-in-first-out) ordering. push A push B push C pop pop pop push D An item removed (pop) from the stack is the last element that was added (push) to the stack. A stack has LIFO (last-in-first-out) ordering. push A push B push C pop pop pop push D Stack inserts followed by stack deletions reverse the order of the elements Stack inserts followed by stack deletions reverse the order of the elements

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Interface The generic Stack interface defines a restricted set of collection operations that access and update only one end of a list. The generic Stack interface defines a restricted set of collection operations that access and update only one end of a list.

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Interface (concluded)

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. ALStack Class The Stack interface is an adapter which defines a restricted set of list methods. A Stack class can be implemented using a List class as the storage structure. The ALStack class uses an ArrayList and composition. The Stack interface is an adapter which defines a restricted set of list methods. A Stack class can be implemented using a List class as the storage structure. The ALStack class uses an ArrayList and composition.

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. ALStack class (continued) public class ALStack implements Stack { // storage structure private ArrayList stackList = null; // create an empty stack by creating // an empty ArrayList public ALStack() { stackList = new ArrayList (); }... }

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing ALStack Method peek() Method has runtime efficiency O(1) Method has runtime efficiency O(1) public T peek() { // if the stack is empty, throw // EmptyStackException if (isEmpty()) throw new EmptyStackException(); // return the element at the back of the ArrayList return stackList.get(stackList.size()-1); }

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing ALStack Method push() Method has runtime efficiency O(1) Method has runtime efficiency O(1) public void push(T item) { // add item at the end of the ArrayList stackList.add(item); }

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing ALStack Method pop() Method has runtime efficiency O(1) Method has runtime efficiency O(1) public T pop() { // if the stack is empty, throw // EmptyStackException if (isEmpty()) throw new EmptyStackException(); // remove and return the last // element in the ArrayList return stackList.remove(stackList.size()-1); }

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Application: Multibase Numbers Multibase numbers use a base for the grouping and digits in their positional and expanded representations. Multibase numbers use a base for the grouping and digits in their positional and expanded representations. E.g. n = 75 with bases 2, 8, 16 E.g. n = 75 with bases 2, 8, 16

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Application Multibase Numbers (continued) An algorithm uses repeated division (n/base) and the mod operator (n % base) to create and extract the digits in reverse order. An algorithm uses repeated division (n/base) and the mod operator (n % base) to create and extract the digits in reverse order. E.g. 75 10 = 113 8 E.g. 75 10 = 113 8

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Application Multibase Numbers (continued) The example illustrates the conversion of the integer n = 431 to base-16 (hex) number string "1AF". The example illustrates the conversion of the integer n = 431 to base-16 (hex) number string "1AF".

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.baseString() public static String baseString(int num, int b) { // digitChar.charAt(digit) is the // character that represents the digit, // 0 <= digit <= 15 String digitChar = "0123456789ABCDEF", numStr = ""; // stack holds the base-b digits of num ALStack stk = new ALStack (); // extract base b digits right // to left and push on stack do { // push right-most digit on the stack stk.push(digitChar.charAt(num % b)); // remove right-most digit from num num /= b; // continue until all digits found } while (num != 0);

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. baseString() (concluded) while (!stk.isEmpty()) // flush the stack { // pop stack and add digit on top // of stack to numStr numStr += stk.pop().charValue(); } return numStr; }

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.1 Program uses the method baseString() Program uses the method baseString() to output the multibase representation of four nonnegative integer values. to output the multibase representation of four nonnegative integer values.

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.1 (continued) import java.util.Scanner; import ds.util.ALStack; public class Program14_1 { public static void main(String[] args) { int num, b; // decimal number and base int i; // loop index // create scanner for keyboard input Scanner keyIn = new Scanner(System.in); for (i = 1; i <= 4; i++) { // prompt for number and base System.out.print("Enter a decimal number: "); num = keyIn.nextInt(); System.out.print("Enter a base (2 to 16): "); b = keyIn.nextInt();

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.1 (concluded) System.out.println(" " + num + " base " + b + " is " + baseString(num, b)); } < listing of baseString() given in the program discussion > }

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.1 (Run) Run: Enter a decimal number: 27 Enter a base (2 to 16): 2 27 base 2 is 11011 Enter a decimal number: 300 Enter a base (2 to 16): 16 300 base 16 is 12C Enter a decimal number: 75 Enter a base (2 to 16): 8 75 base 8 is 113 Enter a decimal number: 10 Enter a base (2 to 16): 3 10 base 3 is 101

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Application Balancing Symbol Pairs A program properly matches and nests the symbol pairs if each right-symbol matches the last unmatched left symbol and all of the symbols are part of a matching pair. A program properly matches and nests the symbol pairs if each right-symbol matches the last unmatched left symbol and all of the symbols are part of a matching pair. Method checkForBalance() uses a stack to test for proper balancing. It returns a string that identifies an unmatched symbol and the location were the mismatch is first recognized. Method checkForBalance() uses a stack to test for proper balancing. It returns a string that identifies an unmatched symbol and the location were the mismatch is first recognized.

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.checkForBalance() public String checkForBalance(String expStr) { // holds left-symbols ALStack s = new ALStack (); int i = 0; char scanCh = ' ', matchCh; String msgStr = ""; while (i < expStr.length()) { // access the character at index i scanCh = expStr.charAt(i);

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. checkForBalance() (continued) // check for left-symbol; if so, push on stack; // otherwise, check for right-symbol and // check balancing if (scanCh == '(' || scanCh == '[' || scanCh == '{') s.push(scanCh); else if(scanCh == ')' || scanCh == ']' || scanCh == '}') { // get character on top of stack; // if stack is empty, catch the exception // and return the error message try { matchCh = s.pop();

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. checkForBalance() (continued) // check for corresponding matching // pair; if match fails, return an // error message if (matchCh == '(' && scanCh != ')' || matchCh == '[' && scanCh != ']' || matchCh == '{' && scanCh != '}') { msgStr += "^"; return "\n" + msgStr + " Missing left symbol"; }

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. checkForBalance() (continued) catch (RuntimeException e) { msgStr += "^"; return "\n" + msgStr + " Missing left symbol"; } i++; msgStr += " "; }

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. checkForBalance() (concluded) // at end of scan, check the stack; if empty, // return message that string is balanced; // otherwise return an error message if (s.isEmpty()) return "\n" + msgStr + " Expression is balanced"; else { msgStr += "^"; return "\n" + msgStr + " Missing right symbol"; }

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.2 The GUI program uses method checkForBalance() to display the correctness of a user supplied expression. The GUI program uses method checkForBalance() to display the correctness of a user supplied expression. The window contains a text field in the NORTH region and a text area is the CENTER region. The window contains a text field in the NORTH region and a text area is the CENTER region. A user enters a string in the text field and presses the Enter key. This creates an action event, similar to a mouse-click in a button. A user enters a string in the text field and presses the Enter key. This creates an action event, similar to a mouse-click in a button. Event handler actionPerformed() inputs the string from the field, calls checkForBalance(), appends the return string in the text area, and clears the text field. Event handler actionPerformed() inputs the string from the field, calls checkForBalance(), appends the return string in the text area, and clears the text field.

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.2 (continued) public void actionPerformed(ActionEvent ae) { // read string from the text field called inputField String testStr = inputField.getText(); // display string in the text area called outputArea outputArea.append(testStr); // call checkForBalance() and display return message outputArea.append(checkForBalance(testStr) + "\n"); // clear the text field for the next input inputField.setText(""); }

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Recursion and the Runtime Stack For method execution, the runtime system creates an activation record for the parameters and return address. For method execution, the runtime system creates an activation record for the parameters and return address. The record is pushed on a runtime stack when the method is called and then popped from the stack when the method finishes execution. The program continues at the return address. The record is pushed on a runtime stack when the method is called and then popped from the stack when the method finishes execution. The program continues at the return address.

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Example: fact() Calling fact() in main: public static void main(String[] args) Calling fact() in main: public static void main(String[] args) { int factValue;... factValue = fact(3); System.out.println("Value fact(3) = "+factValue); } Recursive call in fact(): public static int fact(int n) {if (n == 0) return 1; else return n * fact(n-1); } Recursive call in fact(): public static int fact(int n) {if (n == 0) return 1; else return n * fact(n-1); }

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Example: fact() (continued) An activation record has a field for the integer argument n and a field for the return address. The method does not define any local variables. An activation record has a field for the integer argument n and a field for the return address. The method does not define any local variables.

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Example: fact() (continued) Runtime stack during calling (push) process Runtime stack during calling (push) process

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Example: fact() (concluded) Runtime stack during return (pop) process Runtime stack during return (pop) process

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Postfix Expressions In a postfix evaluation format (RPN) for an arithmetic expression, an operator comes after its operands. Examples: In a postfix evaluation format (RPN) for an arithmetic expression, an operator comes after its operands. Examples: a + b * c RPN: a b c * + Operator * has higher precedence than +. a + b * c RPN: a b c * + Operator * has higher precedence than +. (a + b) * c RPN: a b + c * The parenthesis creates subexpression a b + (a + b) * c RPN: a b + c * The parenthesis creates subexpression a b + (a*b + c) / d + e RPN: a b * c + d/ e + The subexpression is a b * c +. Division is the next operator followed by addition. (a*b + c) / d + e RPN: a b * c + d/ e + The subexpression is a b * c +. Division is the next operator followed by addition.

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Postfix Evaluation To evaluate a postfix expression, execute the following steps until the end of the expression. To evaluate a postfix expression, execute the following steps until the end of the expression. 1. If recognize an operand, push it on the stack. 2. If recognize an operator, pop its operands, apply the operator and push the value on the stack. 3. Upon conclusion, the value of the postfix expression is on the top of the stack.

37 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Postfix Evaluation (continued) Example: evaluate "4 3 5 * +" Example: evaluate "4 3 5 * +"

38 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Postfix Evaluation (continued) At each step in the postfix evaluation algorithm, the state of the stack allows us to identify whether an error occurs and the cause of the error. At each step in the postfix evaluation algorithm, the state of the stack allows us to identify whether an error occurs and the cause of the error.

39 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Postfix Evaluation (continued) In the expression3 8 + * 9 the binary operator * is missing a second operand. Identify this error when reading * with the stack containing only one element. In the expression3 8 + * 9 the binary operator * is missing a second operand. Identify this error when reading * with the stack containing only one element.

40 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Postfix Evaluation (continued) An expression may contain too many operands. Identify this error after processing the entire expression. At the conclusion of the process, the stack contains more than one element. Example: 9 8 + 7 An expression may contain too many operands. Identify this error after processing the entire expression. At the conclusion of the process, the stack contains more than one element. Example: 9 8 + 7

41 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. PostfixEval Class The PostfixEval class provides methods to take a postfix expression and return its value. The key method is evaluate() which uses the private methods compute(), getOperand(), and isOperand(). The PostfixEval class provides methods to take a postfix expression and return its value. The key method is evaluate() which uses the private methods compute(), getOperand(), and isOperand().

42 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.3 This program illustrates postfix expression evaluation using methods from the PostfixEval class This program illustrates postfix expression evaluation using methods from the PostfixEval class

43 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.3 (continued) import java.util.Scanner; public class Program14_3 { public static void main(String[] args) { // object used to evaluate postfix expressions PostfixEval exp = new PostfixEval(); // postfix expression input String rpnExp; // for reading an expression Scanner keyIn = new Scanner(System.in); System.out.print("Enter the postfix " + "expression: "); rpnExp = keyIn.nextLine(); // assign the expression to exp exp.setPostfixExp(rpnExp);

44 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.3 (concluded) // call evaluate() in a try block // in case an error occurs try { System.out.println("The value of the " + "expression = " + exp.evaluate() + "\n"); } // catch block outputs the error catch (ArithmeticException ae) { System.out.println(ae.getMessage() + "\n"); }

45 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 14.3 (Run) Run 1: (2 + 5)*3 - 8/3 Enter the postfix expression: 2 5 + 3 * 8 3 / - The value of the expression = 19 Run 2: 2^3 + 1 Enter the postfix expression: 2 3 ^ 1 + The value of the expression = 9 Run 3: Enter the postfix expression: 1 9 * / PostfixEval: Too many operators Run 4: Enter the postfix expression: 2 3 5 + PostfixEval: Too many operands

46 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval The task of scanning the postfix expression and computing a result is left to the method evaluate() which uses an integer stack, operandStack, to store the operands. The task of scanning the postfix expression and computing a result is left to the method evaluate() which uses an integer stack, operandStack, to store the operands. The evaluate() algorithm uses the private methods isOperand(), getOperand() and compute(). The evaluate() algorithm uses the private methods isOperand(), getOperand() and compute().

47 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) The boolean method isOperand() is called when scanning a non-whitespace character to determine whether it is a valid character ('+','-','*','/','%','^'). The boolean method isOperand() is called when scanning a non-whitespace character to determine whether it is a valid character ('+','-','*','/','%','^'). If so, evaluate() calls getOperand() to retrieve first the right-hand operand and then the left-hand operand. The method throws ArithmeticException if it finds an empty stack. If so, evaluate() calls getOperand() to retrieve first the right-hand operand and then the left-hand operand. The method throws ArithmeticException if it finds an empty stack.ArithmeticException

48 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) An operator is processed using the method compute() which evaluates the operation "left op right" and pushes the result back onto the stack. An operator is processed using the method compute() which evaluates the operation "left op right" and pushes the result back onto the stack.

49 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) int compute(int left, int right, char op) { int value = 0; // evaluate "left op right" switch(op) { case '+': value = left + right; break; case '-': value = left - right; break;... < throw ArithmeticException for divide by 0 or 0^0 > } return value; }

50 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) The main loop in evaluate() scans each character of the postfix expression and terminates when all characters have been processed or when an error occurs. Upon completion, the final result resides at the top of the stack and is assigned to the variable expValue which becomes the return value. The main loop in evaluate() scans each character of the postfix expression and terminates when all characters have been processed or when an error occurs. Upon completion, the final result resides at the top of the stack and is assigned to the variable expValue which becomes the return value.

51 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) int left, right, expValue; char ch; int i; // process characters until the end of the string is reached // or an error occurs for (i=0; i < postfixExpression.length(); i++) { // get the current character ch = postfixExpression.charAt(i);... }

52 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) The scan uses the static method isDigit() from the Character class to determine whether the current character ch is a digit. The static method returns true if ch >= '0' && ch = '0' && ch <= '9'. In this case, evaluate() pushes the corresponding Integer value of the operand onto the stack.

53 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) // look for an operand, which is a single digit // non-negative integer if (Character.isDigit(ch)) // value of operand goes on the stack as Integer object operandStack.push(ch - '0');

54 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) If the current character ch in the scan is an operator, evaluate() initiates a process of extracting the operands from the stack and uses compute() to carry out the calculation and return the result. Push the return value onto the stack. If the current character ch in the scan is an operator, evaluate() initiates a process of extracting the operands from the stack and uses compute() to carry out the calculation and return the result. Push the return value onto the stack.

55 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) // look for an operator else if (isOperator(ch)) { // pop the stack to obtain the right operand right = getOperand(); // pop the stack to obtain the left operand left = getOperand(); // evaluate "left op right" and push on stack operandStack.push(new Integer(compute(left, right, ch))); }

56 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) If the current character ch in the scan is neither an operand nor an operator, evaluate() uses the static method isWhitespace() from the Character class to determine whether ch is a whitespace separator consisting of a blank, newline, or tab. If this is not the case, evaluate() throws an ArithmeticException; otherwise, the loop continues with the next character in the string. If the current character ch in the scan is neither an operand nor an operator, evaluate() uses the static method isWhitespace() from the Character class to determine whether ch is a whitespace separator consisting of a blank, newline, or tab. If this is not the case, evaluate() throws an ArithmeticException; otherwise, the loop continues with the next character in the string.

57 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) // any other character must be whitespace. // whitespace includes blank, tab, and newline else if (!Character.isWhitespace(ch)) throw new ArithmeticException("PostfixEval: Improper char");

58 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (continued) Assuming the scan of the postfix expression terminates without an error, the value of a properly formed expression should be on the top of the stack. The method, evaluate(), pops the value from the stack. If the stack is then empty, the value is the final result. If the stack still contains elements, evaluate() concludes there are too many operands and throws an ArithmeticException. Assuming the scan of the postfix expression terminates without an error, the value of a properly formed expression should be on the top of the stack. The method, evaluate(), pops the value from the stack. If the stack is then empty, the value is the final result. If the stack still contains elements, evaluate() concludes there are too many operands and throws an ArithmeticException.

59 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing PostfixEval (concluded) // the expression value is on the top of the stack. pop it off expValue = operandStack.pop(); // if data remains on the stack, there are too many operands if (!operandStack.isEmpty()) throw new ArithmeticException ("PostfixEval: Too many operands"); return expValue;

60 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix Expression Evaluation In an infix expression, each binary operator appears between its operands and each unary operator precedes its operand. Infix is the most common format for writing expressions and is the expression format of choice for most programming languages and calculators. Evaluation is more difficult than postfix expression evaluation. In an infix expression, each binary operator appears between its operands and each unary operator precedes its operand. Infix is the most common format for writing expressions and is the expression format of choice for most programming languages and calculators. Evaluation is more difficult than postfix expression evaluation.

61 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix Expression Evaluation (continued) The evaluation algorithm must have a strategy to handle subexpressions and must maintain the order of precedence and associativity for operators. For instance, in the expression 9 + (2 - 3) * 8 we evaluate the subexpression (2 - 3) first and then use the result as the left operand for *. The operator * executes before the + operator, because it has higher precedence. The evaluation algorithm must have a strategy to handle subexpressions and must maintain the order of precedence and associativity for operators. For instance, in the expression 9 + (2 - 3) * 8 we evaluate the subexpression (2 - 3) first and then use the result as the left operand for *. The operator * executes before the + operator, because it has higher precedence.

62 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix Expression Evaluation (continued) There are two approaches to infix expression evaluation. There are two approaches to infix expression evaluation. The book's approach converts the infix expression to its equivalent postfix expression and then calls the postfix expression evaluator to compute the result. The book's approach converts the infix expression to its equivalent postfix expression and then calls the postfix expression evaluator to compute the result. Another approach scans the infix expression and uses separate operator and operand stacks to store the terms. The algorithm produces the result directly. Another approach scans the infix expression and uses separate operator and operand stacks to store the terms. The algorithm produces the result directly.

63 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix Expression Attributes Infix expressions consist of operands, operators, and pairs of parentheses that create subexpressions, which are computed separately. Infix expressions consist of operands, operators, and pairs of parentheses that create subexpressions, which are computed separately. The order of precedence dictates that you evaluate the operator with the highest precedence first. The order of precedence dictates that you evaluate the operator with the highest precedence first. Among arithmetic operators, the additive operators (+, -) have the lowest precedence; next are the multiplicative operators (*, /, %). The exponentiation operator (^) has the highest precedence. Among arithmetic operators, the additive operators (+, -) have the lowest precedence; next are the multiplicative operators (*, /, %). The exponentiation operator (^) has the highest precedence.

64 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix Expression Attributes (continued) The concept of associativity refers to the order of execution for operators at the same precedence level. If more than one operator has the same precedence, the leftmost operator executes first in the case of left associativity (+, -,, /, %) and the rightmost operator executes first in the case of right associativity (^). The concept of associativity refers to the order of execution for operators at the same precedence level. If more than one operator has the same precedence, the leftmost operator executes first in the case of left associativity (+, -,, /, %) and the rightmost operator executes first in the case of right associativity (^).

65 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix Expression Attributes (concluded) 7 * 2 * 4 / 5 Evaluate:((7 * 2) * 4) /5 = (14 * 4) / 5 = 56 % 5 = 11 2 ^ 3 ^ 2 + 3 Evaluate: (2 ^ (3 ^ 2)) + 3 = 2 9 + 3 = 512 + 3 = 515

66 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion The infix-to-postfix conversion algorithm takes an infix expression as an input string and returns the corresponding postfix expression as an output (postfix) string. The infix-to-postfix conversion algorithm takes an infix expression as an input string and returns the corresponding postfix expression as an output (postfix) string. The algorithm copies operands to an output string and uses a stack to store and process operators and the left-parenthesis symbol. The algorithm copies operands to an output string and uses a stack to store and process operators and the left-parenthesis symbol. The operator stack manages the order of precedence and associativity of operators and well as handling subexpressions. The operator stack manages the order of precedence and associativity of operators and well as handling subexpressions.

67 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion (continued) The class InfixToPostfix defines methods to convert an infix expression containing single digit integer operands 0-9 and integer operators +, -, *, /, %, and ^ to postfix form. The class InfixToPostfix defines methods to convert an infix expression containing single digit integer operands 0-9 and integer operators +, -, *, /, %, and ^ to postfix form.

68 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion (continued) The GUI application InfixExpressions.java inputs an expression and evaluates the result using the class InfixToPostfix. The GUI application InfixExpressions.java inputs an expression and evaluates the result using the class InfixToPostfix.

69 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues Write an operand to the postfix string. Place an operator on the stack, awaiting its right-hand operand. Write an operand to the postfix string. Place an operator on the stack, awaiting its right-hand operand. Example: Expression a + b * c

70 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues (continued) Push an operator on the stack only after removing all operators of higher or equal precedence. Push an operator on the stack only after removing all operators of higher or equal precedence. Example: Infix expression a * b / c + d

71 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues (continued) Making the input and stack precedence of an operator different allows the handling of an operator that is right associative. Making the input and stack precedence of an operator different allows the handling of an operator that is right associative. Example: Infix expression a^b^c

72 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues (continued) Assign '(' an input precedence that is greater than the stack precedence of any other operator. This allows '(' and the operators in the subexpression to remain on the stack until the algorithm encounters')'. Assign '(' an input precedence that is greater than the stack precedence of any other operator. This allows '(' and the operators in the subexpression to remain on the stack until the algorithm encounters')'.

73 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues (continued) Example: Infix expression a * (b + c)

74 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues (continued)

75 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Infix-to-Postfix Conversion Issues (concluded) A detailed discussion of the infix to postfix conversion algorithm is provided on the Web site http://www.fordtopp.com. A detailed discussion of the infix to postfix conversion algorithm is provided on the Web site http://www.fordtopp.com.http://www.fordtopp.com


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 14 Stacks."

Similar presentations


Ads by Google