41
7/13/2010 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

Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

Embed Size (px)

Citation preview

Page 1: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

1

Data StructuresData Structures

Array Based Stacks

StacksDefinition:

list of homogeneous elementslist of homogeneous elementsaddition and deletion of elements occurs only at one end, called the top of the stack

Last In First Out (LIFO) data structureUsed to implement method callsUsed 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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

2

Various Types of Stacks

CIS265/506: Chapter 04 - Stacks and Queues 3

LIFOLast In First Out (LIFO) data structure

T l t f t k i l t l t t bTop element of stack is last element to be added to stackElements 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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

4

Basic Operations on a StackinitializeStack: Initializes the stack to an

t t tempty stateisEmptyStack: Checks whether the stack is empty. If empty, it returns true; otherwise, it returns falseisFullStack: 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 stackThe input consists of the stack and the new elementPrior to this operation, the stack must exist and must not be full

CIS265/506: Chapter 04 - Stacks and Queues 8

Page 5: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 emptypop: 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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

7

initializeStackpublic 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 fullStackpublic 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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 constructorpublic StackClass()public StackClass() {

maxStackSize = 100;stackTop = 0; //create arraylist = new DataElement[maxStackSize];

CIS265/506: Chapter 04 - Stacks and Queues 22

}//end default constructor

Page 12: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

13

Java class Stack

Java provides a class to implement a stack in a programThe 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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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

Polish Notation got its name from Jan Lukasiewicz, a g ,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 Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

20

Examples

InfixInfix PrefixPrefix PostfixPostfixInfixInfix 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 equation as 8.

Page 21: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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 the 10 and evaluate with the *. The final result

CIS265/506: Chapter 04 - Stacks and Queues 41

is 80.

Evaluating RPN Expressions

It starts to become apparent that we apply the operatorIt 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 10. Apply the - operator to the 3 and 10 (3 - 10) getting -7

CIS265/506: Chapter 04 - Stacks and Queues 42

the 3 and 10 (3 10) getting 7.

Page 22: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

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? We scan our input streamHow about an algorithm? We scan our input stream from left to right, removing the first character as we go. We check the character to see if it is an operator or an operand. If it is an operand, we push it on the stack. If it is an operand, we remove the top two items from the stack, and perform the requested operation. We then push the result back on the stack. If all went well, at the

CIS265/506: Chapter 04 - Stacks and Queues 44

pend of the stream, there will be only one item on the stack - our final result.

Page 23: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

23

Evaluating RPN Expressions

Step Stack RPN Equation Step Stack RPN Equation

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

Converting Infix to PostfixManual Transformation (Continued)

E l 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 parenthesis

CIS265/506: Chapter 04 - Stacks and Queues 46

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

Page 24: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

24

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 47

Step 4: A B C * +

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 48

Remove ParenthesesA B + C * D + E F * + G -

Page 25: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

25

Converting Infix to Postfix

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

Example: A * BThis 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 49

stack, write the B, then get the and write it. So, solution is: A B *

Converting Infix to Postfix

Here are a few things to consider:How to handle operator precedenceWhat about parentheses?What happens if the equation is just typed wrong? (Operator error)

CIS265/506: Chapter 04 - Stacks and Queues 50

Page 26: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

26

Converting Infix to Postfix

How to handle operator precedenceWhat 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 51

Converting Infix to Postfix

P d f tPrecedence for operatorsHighest 2: * /

1: + -

Lowest: 0: (

What abo t closing parentheses? A closing

CIS265/506: Chapter 04 - Stacks and Queues 52

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.

Page 27: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

27

Converting Infix to PostfixBased 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 53

take item from top of stackwhile this item != (

add it to the endof the output string

Cont....

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 54

put the current symbol on top of the stack

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

End loopCont....

Page 28: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

28

Converting Infix to PostfixFinallyWhil ( 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 55

Converting Infix to PostfixWhat about precedence testing?

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

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

return 1;

CIS265/506: Chapter 04 - Stacks and Queues 56

return 1;case operator “(“

return 0;default

return 99; //signals error condition!

Page 29: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

29

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 57

))+E +EE

(-(+-+ + EMPTY

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

Data Structures

Queues

Page 30: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

30

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 59

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 60

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

Page 31: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

31

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 61

only visible value from the queue.

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

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 62

plum apple kiwi grape figrearfront

Physical View of A Queue

Page 32: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

32

Array Based Queues

In the same way we have array based stacks, we can also make array based queuesThere are several ways to look at the implementation problem

We can say that front is always at index 0, while rearcan “float”

CIS265/506: Chapter 04 - Stacks and Queues 63

We can say that rear is always at index 0 and frontcan floatOr, we can imagine a circular array.

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 64

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.

Page 33: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

33

Queue Operations

CIS265/506: Chapter 04 - Stacks and Queues 65

Create Queue

Creates an initialized head node for an empty queue

CIS265/506: Chapter 04 - Stacks and Queues 66

Page 34: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

34

No QueueFront Ptr Rear Ptr

0count

?

CIS265/506: Chapter 04 - Stacks and Queues 67

before after

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 68

Page 35: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

35

Front Ptr Rear Ptr

1countFront Ptr Rear Ptr

0count

plumdata next

CIS265/506: Chapter 04 - Stacks and Queues 69

before after

Front Ptr Rear Ptr

2countFront Ptr Rear Ptr

1count

plumdata next

plumdata next

appledata next

CIS265/506: Chapter 04 - Stacks and Queues 70

before after

Page 36: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

36

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 71

q

Front Ptr Rear Ptr

1count

Front Ptr Rear Ptr

2count

appledata next

2

plumdata next

appledata next

CIS265/506: Chapter 04 - Stacks and Queues 72

before after

Page 37: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

37

Destroy Queue

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

CIS265/506: Chapter 04 - Stacks and Queues 73

No QueueFront Ptr Rear Ptr

1count

?appledata next

CIS265/506: Chapter 04 - Stacks and Queues 74

before after

Page 38: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

38

“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 75

“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 76

Page 39: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

39

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 77

if (allocation successful)recycle(tempPtr)return false

elsereturn true

Java takes care of most of this for us.

Other Algorithms

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

Return queue->count

CIS265/506: Chapter 04 - Stacks and Queues 78

Page 40: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

40

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 79

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

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 80

2

Page 41: Data StructuresData Structures - csuohio.educis.csuohio.edu/~matos/notes/cis-265/BeckyGrasserNotes/PPT_Slides/... · 7/13/2010 1 Data StructuresData Structures Array Based Stacks

7/13/2010

41

EfficiencyEfficient 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 81

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