Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... ·...

44
8/1/2011 1 Data Structures Data Structures Array Based Stacks Stacks Definition: list of homogeneous elements list of homogeneous elements addition and deletion of elements occurs only at one end, called the top of the stack Last In First Out (LIFO) data structure Used to implement method calls Used to convert recursive algorithms CIS265/506: Chapter 04 - Stacks and Queues 2 Used to convert recursive algorithms (especially non-tail recursive) into nonrecursive algorithms

Transcript of Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... ·...

Page 1: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

1

Data StructuresData Structures

Array Based Stacks

Stacks Definition: list of homogeneous elements list of homogeneous elements addition and deletion of elements occurs only

at one end, called the top of the stack

Last In First Out (LIFO) data structure Used to implement method calls Used to convert recursive algorithms

CIS265/506: Chapter 04 - Stacks and Queues 2

Used to convert recursive algorithms (especially non-tail recursive) into nonrecursive algorithms

Page 2: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

2

Various Types of Stacks

CIS265/506: Chapter 04 - Stacks and Queues 3

LIFO Last In First Out (LIFO) data structure

T l t f t k i l t l t t b Top element of stack is last element to be added to stack

Elements added and removed from one end (top)

Item added last are removed first

CIS265/506: Chapter 04 - Stacks and Queues 4

Page 3: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

3

Empty Stack

CIS265/506: Chapter 04 - Stacks and Queues 5

Stack Operations

CIS265/506: Chapter 04 - Stacks and Queues 6

Page 4: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

4

Basic Operations on a Stack

initializeStack: Initializes the stack to an t t tempty state

isEmptyStack: Checks whether the stack is empty. If empty, it returns true; otherwise, it returns false

isFullStack: Checks whether the stack is full. If full it returns true; otherwise it returns

CIS265/506: Chapter 04 - Stacks and Queues 7

If full, it returns true; otherwise, it returns false

Basic Operations on a Stack

push: Add new element to the top of the stack

The input consists of the stack and the new element

Prior to this operation, the stack must exist and must not be full

CIS265/506: Chapter 04 - Stacks and Queues 8

Page 5: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

5

Basic Operations on a Stack

top: Returns the top element of the stack. Prior to this operation, the stack must exist and must not be empty

pop: Removes the top element of the stack. Prior to this operation, the stack must exist and must not be empty

CIS265/506: Chapter 04 - Stacks and Queues 9

p y

Efficiency

Efficient Array Implementation of a stack means making use of how arrays work. When pushing, add an element to the end of the

used elements in the array.

When popping, do the reverse.

Now, push and pop are both O(1)

CIS265/506: Chapter 04 - Stacks and Queues 10

Doing it the other way is not O(1) unless some kind of a circular (more later) stack is used

Page 6: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

6

Example of a Stack

CIS265/506: Chapter 04 - Stacks and Queues 11

Empty Stack

CIS265/506: Chapter 04 - Stacks and Queues 12

Page 7: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

7

initializeStack

public void initializeStack(){{

for(int i = 0; i < stackTop; i++)list[i] = null;

stackTop = 0;}//end initializeStack

CIS265/506: Chapter 04 - Stacks and Queues 13

emptyStack and fullStack

public boolean isEmptyStack(){{

return(stackTop == 0);}//end isEmptyStack

public boolean isFullStack()

{

CIS265/506: Chapter 04 - Stacks and Queues 14

{

return(stackTop == maxStackSize);

}//end isFullStack

Page 8: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

8

Push

CIS265/506: Chapter 04 - Stacks and Queues 15

Push

public void push(DataElement newItem) throws k fl iStackOverflowException

{if(isFullStack())

throw new StackOverflowException();

//add newItem at the top of the stacklist[stackTop] = newItem.getCopy(); //increment stackTop

CIS265/506: Chapter 04 - Stacks and Queues 16

//increment stackTopstackTop++;

}//end push

Page 9: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

9

Return Top Element

bli D t El t t () th St kU d fl E tipublic DataElement top() throws StackUnderflowException{

if(isEmptyStack())throw new StackUnderflowException();

DataElement temp = list[stackTop - 1].getCopy();return temp;

}//end top

CIS265/506: Chapter 04 - Stacks and Queues 17

}// p

Pop

public void pop() throws StackUnderflowException{

if(isEmptyStack())throw new StackUnderflowException();

stackTop--; //decrement stackToplist[stackTop] = null;

CIS265/506: Chapter 04 - Stacks and Queues 18

}//end pop

Page 10: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

10

Pop

CIS265/506: Chapter 04 - Stacks and Queues 19

copy

private void copy(StackClass otherStack){

list = null;System.gc();maxStackSize = otherStack.maxStackSize; stackTop = otherStack.stackTop; list = new DataElement[maxStackSize];

//copy otherStack into this stack

CIS265/506: Chapter 04 - Stacks and Queues 20

for(int i = 0; i < stackTop; i++) list[i] = otherStack.list[i].getCopy();

}//end copy6

Page 11: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

11

Constructors//constructor with a parameter

public StackClass(int stackSize) {

if(stackSize <= 0){

System.err.println(“The size of the array to implement “+ “the stack must be positive.”);

System.err.println(“Creating an array of size 100.”);maxStackSize = 100;

}else

maxStackSize = stackSize; //set the stack size to //the value specified by //th t t kSi

CIS265/506: Chapter 04 - Stacks and Queues 21

//the parameter stackSizestackTop = 0; //set stackTop to 0list = new DataElement[maxStackSize]; //create the array

}//end constructor

Constructors

//default constructor

public StackClass()public StackClass()

{

maxStackSize = 100;

stackTop = 0;

//create array

list = new DataElement[maxStackSize];

CIS265/506: Chapter 04 - Stacks and Queues 22

}//end default constructor

Page 12: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

12

Copy Constructor and copyStack

public StackClass(StackClass otherStack){

copy(otherStack);}//end copy constructor

public void copyStack(StackClass otherStack){

CIS265/506: Chapter 04 - Stacks and Queues 23

{if(this != otherStack) //avoid self-copy

copy(otherStack);}//end copyStack

Time Complexity of Operations of class stackType

CIS265/506: Chapter 04 - Stacks and Queues 24

Page 13: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

13

Java class Stack

Java provides a class to implement a stack in a program

The name of the Java class defining a stack is Stack

The class Stack is contained in the package java.util

CIS265/506: Chapter 04 - Stacks and Queues 25

java.util

Java class Stack

CIS265/506: Chapter 04 - Stacks and Queues 26

Page 14: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

14

Empty and Nonempty Linked Stack

CIS265/506: Chapter 04 - Stacks and Queues 27

Empty linked stack Nonempty linked stack

Default Constructor

public LinkedStackClass()

{

stackTop = null;

}

CIS265/506: Chapter 04 - Stacks and Queues 28

Page 15: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

15

initializeStack, isStackEmpty, and isStackFull

public void initializeStack(){{

stackTop = null;}//end initializeStack

public boolean isEmptyStack(){

return(stackTop == null);}

CIS265/506: Chapter 04 - Stacks and Queues 29

}public boolean isFullStack(){

return false;}

Push

Stack before the pushoperation

Stack and newNode

CIS265/506: Chapter 04 - Stacks and Queues 30

operation

Page 16: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

16

Push

CIS265/506: Chapter 04 - Stacks and Queues 31

Stack after the statement newNode.link = stackTop;executes

Stack after the statement stackTop = newNode;executes

Return Top Element

public DataElement top() throws StackUnderflowException{

if(stackTop == null)throw new StackUnderflowException();

return stackTop.info.getCopy();}//end top

CIS265/506: Chapter 04 - Stacks and Queues 32

Page 17: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

17

Pop

Stack after the statementstackTop = stackTop.link; executes

CIS265/506: Chapter 04 - Stacks and Queues 33

Stack before the pop operation Stack after popping the top element

Data Structures

Stack Implementation of

Prefix, Infix & Postfix

Page 18: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

18

Basic Definitions

There are many ways to write (and evaluate) mathematical equations The first called infix notationmathematical equations. The first, called infix notation, is what we are familiar with from elementary school:

(5*2)-(((3+4*7)+8/6)*9)

You would evaluate this equation from right to left, taking in to account precedence. So:

10 (((3+28)+1 33)*9)

CIS265/506: Chapter 04 - Stacks and Queues 35

10 - (((3+28)+1.33)*9)10 - ((31 + 1.33)*9)10 - (32.33 * 9)10 - 291-281

Basic Definitions

An alternate method is postfix or Reverse Polish NotationAn alternate method is postfix or Reverse Polish Notation (RPN). The corresponding RPN equation would be:

5 2 * 3 4 7 * + 8 6 / + 9 * -

We’ll see how to evaluate this in a minute.

CIS265/506: Chapter 04 - Stacks and Queues 36

Page 19: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

19

Basic Definitions

Note that in an infix expression the operators appearNote that in an infix expression, the operators appear in between the operands (1 + 2).

Postfix equations have the operators after the equations (1 2 +).

In Forward Polish Notation or prefix equations, the operators appear before the operands. The prefix form

CIS265/506: Chapter 04 - Stacks and Queues 37

operators appear before the operands. The prefix form is rarely used (+ 1 2).

Basic Definitions

Reversed Polish Notation got its name from gJan Lukasiewicz, a Polish mathematician, who first published in 1951. Lukasiewicz was a pioneer in three-valued propositional calculus, he also was interested in developing a parenthesis-free method of representing logic expressions. Today, RPN is used in many compilers and interpreters as an intermediate form for representing logic.

CIS265/506: Chapter 04 - Stacks and Queues 38

http://www-groups.dcs.st-and.ac.uk/~history/PictDisplay/Lukasiewicz.html

University of St. Andrews.

Page 20: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

20

Examples

InfixInfix PrefixPrefix PostfixPostfix

RPN expressions

InfixInfix PrefixPrefix PostfixPostfixA+B +AB AB+A+B*C +A*BC ABC*+A*(B+C) *A+BC ABC+*A*B+C +*ABC AB*C+A+B*C+D-E*F -++A*BCD*EF ABC*+D+EF*-(A+B)*(C+D-E)*F **+AB-+CDEF AB+CD+E-*F*

CIS265/506: Chapter 04 - Stacks and Queues 39

(A+B) (C+D-E) F +AB-+CDEF AB+CD+E- F

Evaluating RPN Expressions

We evaluate RPN using a left-to-right scan.

A t i d d b t d tAn operator is preceded by two operands, so we store the first operand, then the second, and once the operator arrives, we use it to compute or evaluate the two operands we just stored.

3 5 +

CIS265/506: Chapter 04 - Stacks and Queues 40

Store the value 3, then the value 5, then using the + operator, evaluate the pending calculation as 8.

Page 21: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

21

Evaluating RPN Expressions

What happens if our equation has more than one operator? Now we’ll need a way to store the intermediate result as well:

3 5 + 10 *

Store the 3, then 5. Evaluate with the +, getting 8.

Store the 8 then store10 when * arrives evaluate the

CIS265/506: Chapter 04 - Stacks and Queues 41

Store the 8, then store10, when arrives evaluate the expression using the previous two arguments.

The final result is 80.

Evaluating RPN Expressions

It starts to become apparent that we apply the operator toIt starts to become apparent that we apply the operator to the last two operands we stored. Example:

3 5 2 * -

Store the 3, then the 5, then the 2.

Apply the * to the 5 and 2, getting 10. Store the value 10.

CIS265/506: Chapter 04 - Stacks and Queues 42

Apply the - operator to the stored values 3 and 10 (3 - 10) getting -7.

Page 22: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

22

Evaluating RPN Expressions

We have been saving values in such a way that the lastWe have been saving values in such a way that the last two values saved become the first two retrieved.

Remember stacks? They are last-in, first-out lists….. Exactly

CIS265/506: Chapter 04 - Stacks and Queues 43

what we need for this application!

Evaluating RPN Expressions

How about an algorithm to evaluate an RPN expression?

1. We scan our input stream from left to right, removing the first character as we go.

2. We check the character to see if it is an operator or an operand.

3. If it is an operand, we push it on the stack.

4. If it is an operator, we remove the top two items from the stack, and perform the requested operation.

CIS265/506: Chapter 04 - Stacks and Queues 44

p q p

5. We then push the result back on the stack.

6. If all went well, at the end of the stream, there will be only one item on the stack - our final result.

Page 23: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

23

Evaluating RPN Expressions

Step Stack RPN Expression Step Stack RPN Expression

4

1

2

3

6

7

8

3 5 + 2 4 - * 6 *

5 + 2 4 - * 6 * * 6 *

+ 2 4 - * 6 *

- * 6 *

6 *

3

53

8

428

-28

-16

CIS265/506: Chapter 04 - Stacks and Queues 45

4

5

9

10

2 4 - * 6 *

4 - * 6 *

*

8

28

6-16

-96

Evaluating RPN Expressions 1/3

package csu.matos;import java.util.Stack;import java.util.StringTokenizer;

public class Driver {

public static void main(String[] args) {public static void main(String[] args) {// Taken from Daniel Liang – Intro to Java Prog.// the input is a correct postfix expression

String expression = "1 2 + 3 *";

try {System.out.println( evaluateExpression(expression) );

}catch (Exception ex) {

System.out.println("Wrong expression");}

}

46

/** Evaluate an expression */public static int evaluateExpression(String expression) {

// Create operandStack to store operandsStack<Integer> operandStack = new Stack<Integer>();

// Extract operands and operatorsStringTokenizer tokens = new StringTokenizer(expression, " +-/*%", true);

Page 24: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

24

Evaluating RPN Expressions 2/3

// Phase 1: Scan tokenswhile (tokens.hasMoreTokens()) {

String token = tokens.nextToken().trim(); // Extract a tokenif (token.length() == 0) { // Blank space

continue; // Back to the while loop to extract the next token}}else if (token.charAt(0) == '+' || token.charAt(0) == '-' ||

token.charAt(0) == '*' || token.charAt(0) == '/') {processAnOperator(token.charAt(0), operandStack);

}else { // An operand scanned

// Push an operand to the stackoperandStack.push(new Integer(token));

}}

// Return the resultreturn ((Integer)(operandStack.pop())).intValue();

47

}

Evaluating RPN Expressions 3/3

/** Process one opeator: Take an operator from operatorStack and* apply it on the operands in the operandStack */

public static void processAnOperator(char op, Stack operandStack) {if (op == '+') {

int op1 = ((Integer)(operandStack.pop())).intValue();int op2 = ((Integer)(operandStack pop())) intValue();int op2 = ((Integer)(operandStack.pop())).intValue();operandStack.push(new Integer(op2 + op1));

}else if (op == '-') {

int op1 = ((Integer)(operandStack.pop())).intValue();int op2 = ((Integer)(operandStack.pop())).intValue();operandStack.push(new Integer(op2 - op1));

}else if ((op == '*')) {

int op1 = ((Integer)(operandStack.pop())).intValue();int op2 = ((Integer)(operandStack.pop())).intValue();operandStack.push(new Integer(op2 * op1));

}

48

else if (op == '/') {int op1 = ((Integer)(operandStack.pop())).intValue();int op2 = ((Integer)(operandStack.pop())).intValue();operandStack.push(new Integer(op2 / op1));

}}

}

Page 25: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

25

Converting Infix to PostfixManual Transformation (Continued)

Example: A + B * CExample: A B C Step 1: (A + ( B * C ) )

Change all infix notations in each parenthesis to postfix notation starting from the innermost expressions. This is done by moving the operator to the location of the expression’s closing

h i

CIS265/506: Chapter 04 - Stacks and Queues 49

parenthesis

Step 2: ( A + ( B C * ) ) Step 3: ( A ( B C * ) + )

Converting Infix to Postfix

Manual Transformation (Continued) Example: A + B * C

Step 2: (A + ( B * C ) )

Step 3: (A ( B C * ) + )

Remove all parenthesesSt 4 A B C * +

CIS265/506: Chapter 04 - Stacks and Queues 50

Step 4: A B C * +

Page 26: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

26

Converting Infix to Postfix

Another Example (A + B ) * C + D + E * F - G

Add Parentheses ( ( ( ( ( A + B ) * C ) + D ) + ( E * F ) ) - G )

Move Operators ( ( ( ( ( A B + ) C * ) D + ) ( E F * ) + ) G - )

CIS265/506: Chapter 04 - Stacks and Queues 51

Remove Parentheses A B + C * D + E F * + G -

Converting Infix to Postfix

This looks very difficult to write a computer program to solve this problem. Lets try again

Example: A * B This looks easy. Write the A, store the * on a

stack, write the B, then get the * and write it.

CIS265/506: Chapter 04 - Stacks and Queues 52

stack, write the B, then get the and write it.

So, solution is: A B *

Page 27: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

27

Converting Infix to Postfix

Here are a few things to consider: How to handle operator precedence

What about parentheses?

What happens if the equation is just typed wrong? (Operator error)

CIS265/506: Chapter 04 - Stacks and Queues 53

Converting Infix to Postfix

How to handle operator precedence

What about parentheses? Fortunately, we can handle these situations in

one step.

Let us assume the parentheses are an operator.

CIS265/506: Chapter 04 - Stacks and Queues 54

Page 28: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

28

Converting Infix to Postfix

P d f tPrecedence for operators

Highest 2: * /

1: + -

Lowest: 0: (

What abo t closing parentheses? A closing

CIS265/506: Chapter 04 - Stacks and Queues 55

What about closing parentheses? A closing parenthesis always signals the end of an expression or sub-expression. We will see in a minute how to handle this.

Converting Infix to Postfix

Based on what we know so far, here is the basic l ith f ialgorithm for conversion

while there is more dataget the first symbol

if symbol = (put it on the stack

if symbol = )

CIS265/506: Chapter 04 - Stacks and Queues 56

take item from top of stackwhile this item != (

add it to the endof the output string

Cont....

Page 29: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

29

Converting Infix to Postfixif symbol is +, -, *, \

look at top of the stackpwhile (stack is not empty AND the priority of the

current symbol is less than OR equal to the priority of the symbol on top of the stack )

Get the stack item and add it tothe end of the output string;

put the current symbol on top of the stack

CIS265/506: Chapter 04 - Stacks and Queues 57

put the current symbol on top of the stack

if symbol is a characteradd it to the end of the output string

End loopCont....

Converting Infix to Postfix

FinallyWhil ( k i )While ( stack is not empty )

Get the next item from the stack and place itat the end of the output string

End

CIS265/506: Chapter 04 - Stacks and Queues 58

Page 30: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

30

Converting Infix to Postfix

What about precedence testing?

Function precedence_test (operator)case operator “*” OR “/”

return 2;case operator “+” OR “-”

return 1;

CIS265/506: Chapter 04 - Stacks and Queues 59

return 1;case operator “(“

return 0;default

return 99; //signals error condition!

Converting Infix to Postfix

I t B ff O t St k O t t St i

The line we are analyzing is: A*B-(C+D)+E

Input Buffer*B-(C+D)+E B-(C+D)+E-(C+D)+E (C+D)+EC+D)+E +D)+ED)+E

Operator Stack EMPTY**--(-( -(+

Output StringAAA B A B *A B *A B * C A B * C

CIS265/506: Chapter 04 - Stacks and Queues 60

))+E +EE

(-(+-+ + EMPTY

A B * C DA B * C D + A B * C D + -A B * C D + - EA B * C D + - E +

Page 31: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

31

Converting Infix to Postfix 1/4

public static void main(String[] args) {// Provide a correct infix expression to be convertedString expression = "( 1 + 2 ) * 3";

try {System.out.println(infixToPostfix(expression));

}catch (Exception ex) {

System.out.println("Wrong expression");}

}

public static String infixToPostfix(String expression) {// Result stringString s = "";

// Create operandStack to store operands

61

// Create operandStack to store operandsStack operandStack = new Stack();

// Create operatorStack to store operatorsStack operatorStack = new Stack();

// Extract operands and operatorsStringTokenizer tokens = new StringTokenizer(expression, "()+-/*%", true);

Converting Infix to Postfix 2/4

// Phase 1: Scan tokenswhile (tokens.hasMoreTokens()) {

String token = tokens.nextToken().trim(); // Extract a token

if (token.length() == 0) { // Blank spacecontinue; // Back to the while loop to extract the next token

}else if (token.charAt(0) == '+' || token.charAt(0) == '-') {

// Process all +, -, *, / in the top of the operator stackwhile (!operatorStack.isEmpty() &&

(operatorStack.peek().equals('+') ||operatorStack.peek().equals('-') ||operatorStack.peek().equals('*') ||operatorStack.peek().equals('/'))) {s += operatorStack pop() + " ";

62

s += operatorStack.pop() + " ";}

// Push the incoming + or - operator into the operator stackoperatorStack.push(new Character(token.charAt(0)));

}

Page 32: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

32

Converting Infix to Postfix 3/4

else if (token.charAt(0) == '*' || token.charAt(0) == '/') {// Process all *, / in the top of the operator stackwhile (!operatorStack.isEmpty() &&

(operatorStack.peek().equals('*') ||operatorStack.peek().equals('/'))) {

s += operatorStack.pop() + " ";}

// Push the incoming * or / operator into the operator stackoperatorStack.push(new Character(token.charAt(0)));

}else if (token.trim().charAt(0) == '(') {

operatorStack.push(new Character('(')); // Push '(' to stack}else if (token.trim().charAt(0) == ')') {

// Process all the operators in the stack until seeing '('

63

// Process all the operators in the stack until seeing '('while (!operatorStack.peek().equals('(')) {

s += operatorStack.pop() + " ";}

operatorStack.pop(); // Pop the '(' symbol from the stack}else { // An operand scanned

// Push an operand to the stacks += token + " ";

}}

Converting Infix to Postfix 4/4

// Phase 2: process all the remaining operators in the stackwhile (!operatorStack.isEmpty()) {

s += operatorStack.pop() + " ";}

// Return the resultreturn s;

}

64

Page 33: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

33

Data Structures

Queues

Queues

Think of a queue as a waiting line at bank or store. Customers are served in the order they arrive, that is, the first person to arrive is the first person served. A queue is a FIRST-IN, FIRST-OUT structure.

For that reason, queues are commonly called FIFO structures.

CIS265/506: Chapter 04 - Stacks and Queues 66

Page 34: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

34

Queues

A queue is a collection of items holding the followingA queue is a collection of items holding the following properties:

• Items are somehow ordered in the collection

• Only one item, called the front element, can be removed from the collection

N it b dd d t th ll ti l t

CIS265/506: Chapter 04 - Stacks and Queues 67

• New items can be added to the collection only at the other end - called the back or rear of the queue

Queues

New Values HereView Data Here

100 25 33 5020012

Front Back

100 is the l i ibl

A new value can

CIS265/506: Chapter 04 - Stacks and Queues 68

only visible value from the queue.

only be added after (“behind”) the 50.

Page 35: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

35

Queue Data Structures

plum apple kiwi grape fig

front rearplum apple kiwi grape fig

Conceptual View of A Queue

Head NodeFront Ptr Rear Ptr

5count

CIS265/506: Chapter 04 - Stacks and Queues 69

plum apple kiwi grape figrearfront

Physical View of A Queue

Array Based Queues

In the same way we have array based stacks, we can also make array based queues

There are several ways to look at the implementation problem We can say that front is always at index 0, while rear

can “float”

CIS265/506: Chapter 04 - Stacks and Queues 70

We can say that rear is always at index 0 and frontcan float

Or, we can imagine a circular array.

Page 36: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

36

Types of Queues

0Queue.front is always zero, shift elements left on dequeue

0Queue.rear is always zero, shift elements right on enqueue

0

CIS265/506: Chapter 04 - Stacks and Queues 71

0In a circular representation, we start front and read at zero. As an element is added, we increment the rear value. When one is deleted, we increment the front value. We need to make sure we “wrap” around the array, to give the illusion of a circle.

Queue Operations

CIS265/506: Chapter 04 - Stacks and Queues 72

Page 37: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

37

Create Queue

Creates an initialized head node for an empty queue

CIS265/506: Chapter 04 - Stacks and Queues 73

No QueueFront Ptr Rear Ptr

0count

?

CIS265/506: Chapter 04 - Stacks and Queues 74

before after

Page 38: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

38

Enqueue

Inserts an element at the rear of the queue

If queue is built as an array, enqueue could cause an OVERFLOW condition.

CIS265/506: Chapter 04 - Stacks and Queues 75

Front Ptr Rear Ptr

1countFront Ptr Rear Ptr

0count

plumdata next

CIS265/506: Chapter 04 - Stacks and Queues 76

before after

Page 39: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

39

Front Ptr Rear Ptr

2countFront Ptr Rear Ptr

1count

plumdata next

plumdata next

appledata next

CIS265/506: Chapter 04 - Stacks and Queues 77

before after

Dequeue

The data at the front of the queue are removed and returned to the user. Similar to “pop” from stacks

Attempting to remove data from an empty queue results in an UNDERFLOW.

CIS265/506: Chapter 04 - Stacks and Queues 78

q

Page 40: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

40

Front Ptr Rear Ptr

1count

Front Ptr Rear Ptr

2count

appledata next

2

plumdata next

appledata next

CIS265/506: Chapter 04 - Stacks and Queues 79

before after

Destroy Queue

Deletes all data from the queue, and returns all allocated memory to the heap

CIS265/506: Chapter 04 - Stacks and Queues 80

Page 41: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

41

No QueueFront Ptr Rear Ptr

1count

?appledata next

CIS265/506: Chapter 04 - Stacks and Queues 81

before after

“peekFront”

This operation allows the program to view the data at the front of the queue, withoutwithoutdestroying the state of the queue.

CIS265/506: Chapter 04 - Stacks and Queues 82

Page 42: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

42

“peekRear”

This operation, similar to “queue front”, allows the program to view the data at the rearrear of the queue. The state of the queue is not altered.

CIS265/506: Chapter 04 - Stacks and Queues 83

Other Queue Methods

Empty Queue - Is the queue empty?

Return (Does queue->count equal zero?)

Full Queue - Is the queue full?

Allocate (tempPtr)if (allocation s ccessf l)

Old style allocations –

Java takes care of

CIS265/506: Chapter 04 - Stacks and Queues 84

if (allocation successful)recycle(tempPtr)return false

elsereturn true

Java takes care of most of this for us.

Page 43: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

43

Other Algorithms

Queue count - how many elements are in the queue?Q y q

Return queue->count

CIS265/506: Chapter 04 - Stacks and Queues 85

Priority Queues

Priority queues are simply partially sorted queues

The order depends on the implementation

I ti d d l ti littl t i ki

CIS265/506: Chapter 04 - Stacks and Queues 86

Inserting and deleting are a little trickier, as you need to take order into account

Page 44: Data StructuresData Structurescis.csuohio.edu/~matos/notes/cis-265/lecture-notes/10-Chapter04... · Used to convert recursive algorithms ... Infix Prefix Postfix RPN expressions A+B

8/1/2011

44

Circular Queue

A Circular Queue is a “regular” queue, but the enqueue and the dequeue can wrap around ends of the array by using modulus operation.

0

1

n

n - 1

CIS265/506: Chapter 04 - Stacks and Queues 87

2

Efficiency

Efficient Array Implementation of a queue means ki f i lmaking use of a circular queue.

When enqueing, add an element to the end of the used elements in the array with modulus for wrap around.

When dequeing, remove an element from the beginning of the used elements in the array.

Doing this ensures enqueue and dequeue are both O(1)

O( ) f f

CIS265/506: Chapter 04 - Stacks and Queues 88

Doing it the other way can only be O(1) for one of those methods, the other is O(N)