Revisit Stack ADT with Exceptions - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

Revisit Stack ADT with Exceptions

Description:

Define the method that has a potential of causing the exception with 'throws' ... throws' clause is optional (See pop() in Stack) ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 11
Provided by: scienceand1
Category:

less

Transcript and Presenter's Notes

Title: Revisit Stack ADT with Exceptions


1
Revisit Stack ADT with Exceptions
  • CSE116

2
Exceptional Handling
  • Create an exception class or hierarchy of
    exception classes to handle application-dependent
    exceptions. Ex RunTimeException,
    EmptyStackException
  • Define the method that has a potential of causing
    the exception with throws primitive at the
    header and inside the method test the condition
    for throwing exception and throw the
    exception (object). throws clause is optional
    (See pop() in Stack)
  • throws clause in the method definition forces
    the method call to be enclosed within try block
    followed by catch blocks where the exception can
    be caught and handled.

3
java.util.Stack
  • It has EmptyStackException which is a subclass of
    RunTimeException
  • Lets study the code for the EmptyStackException
    class, Stack class, and an application.

4
Applications
  • Stack
  • Balancing parenthesis
  • Postfix expression evaluation
  • Language recognizers
  • Traversing a maze
  • Queue
  • Infix expression evaluation
  • Queuing analysis

5
Arithmetic expressions
  • Infix expressionOperator in between operands
  • Ex A B, (A B (C D)B)
  • Postfix expression Operator after the operand
  • Prefix Operator in front of the operands
  • Note Operators are binary operators with two
    operands.

6
Postfix Evaluation
  • 1. Scan elements of the postfix expression left
    to right
  • 1.1 If element is operand s.push(element)
  • 1.2 else if element is operator
  • 1.2.1 op2 s.pop()
  • 1.2.2 op1 s.pop()
  • 1.2.3 result op1 operator op2
  • 1.2.4 s.push(result)
  • 2. Value of the postfix expression s.pop()

7
Infix to postfix conversion
  • Infix expression of format
  • ( 5 6 ) ( 8 10 (8 4))
  • Use a Queue q and Stack s
  • Only binary operations operations with two
    operands

8
Algorithm
  • Scan elements of expression from left to right.
  • Case element of
  • 2.1 operand q.add(element)
  • 2.2 ( s.push(()
  • 2.3 ) 2.3.1 x s.pop()
  • 2.3.2 while (x ! ()
  • q.add(x)
  • x s.pop()

9
Algorithm (contd.)
  • 2.4 operator
  • 2.4.1 x s.top()
  • 2.4.2 while !(xs precedence lt operator) x
    ( s.empty() )
  • q.enque(s.pop())
  • x s.top()
  • 2.4.3 s.push(operator)
  • 3. while (!s.empty())
  • q.enque(s.pop())
  • 4. Queue q has the postfix expression.

10
To be continued.
Write a Comment
User Comments (0)
About PowerShow.com