0% found this document useful (0 votes)
10 views66 pages

DS-Unit2

Uploaded by

buffertimeplay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views66 pages

DS-Unit2

Uploaded by

buffertimeplay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Unit 2 Stack and Queue

Dr.A.Thomas Paul Roy


Professor, Dept. of CSE.,
PSNA CET.

Syllabus
Stack ADT
Operations
Applications
Infix to Postfix Conversion
Evaluating arithmetic expressions
Tower of Hanoi
Queue ADT-Operations
Circular queue implementation
DeQueue
Applications of queues

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Course Outcome

CO2: Develop algorithms to solve problems


using stack and queue data structures

Introduction
Key points to be remembered
Data structure
Types
Liner Vs. Non-linear
Examples

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Introduction
Example
Array
Linked list
Stack
Queue

Stack
Key points to be remembered
Stack
Basic operations
Scenario
Stack applications
Implementation
Issues with Array implementation

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Key points to be remembered
It is a linear data structure in which
insertions & deletions are made at one end
called “top”

It is a special kind of list in which insertions


and deletions takes place at one end called
“top”

“Stack” is an ordered collection of items into


which new items may be inserted and from
which items may be deleted at one end
called “top” of the stack

Stack
Key points to be remembered
LIFO (Last In First Out)

Pushdown list

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Operations involved
2 basic operations
1. Push
2. pop

Stack
Operations involved
1. Push
It is the operation used to insert the data
element at the top of the stack

2. Pop
It is the operation used to delete the data
element from the top of the stack

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Operations involved
Assume a stack is implemented using an
array and the data items 10, 20 & 30 are
inserted in sequence. This can be pictured as

30 20 10

30 top

20 top

10 top

top

Stack
Key points to be remembered
Stack can be referred as “dynamic structure”
coz’ of its frequent insertion & deletion
operations

i.e., during
Push – size of the stack increases
Pop – size of the stack shrinks

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Key points to be remembered
How does a stack changes?
With reference to the definition of stack,
the data items may be inserted at the top
of the stack in that case stack moves
upward to the highest element.

Similarly, Data items can be removed from


the top of the stack in that case Stack
moves downward to the lowest element

For each successive insertion & deletion


operations, the stack expands & shrinks with
the passage of time

Stack
Primitive operations
Basically there are 2 operations that can be
performed on top of the stack namely push &
pop.

For Ex: consider there is a stack “s” from


which you want to insert the data item “i” to
the stack. This can be specified as
Push(s,i) – Function used to insert a data
item “i” to the top of the stack “s”

Pop(s) – Function used to remove data


item “i” from the top of the stack “s”

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Primitive operations
Empty(s) – This function is used to say
whether a stack is empty or not. It results
Boolean value as either true or false

Stacktop(s) – This function returns the top


element of the stack

Stack
Applications of Stack
System Stack
Evaluation of an Expression – 3 types
Evaluation of Infix expression
Evaluation of Postfix expression (Reverse
Polish)
Evaluation of Prefix expression (Polish)
Towers of Hanoi Puzzle
Checking Balanced Parenthesis from the
given expression

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Key points to be remembered: Implementation
Can be done by 2 ways
1. Array Implementation
2. Linked List implementation (Pointer)

Stack
Implementation: Issues with an Array
These conditions will occur if a stack is
implemented using an array

Underflow: It is a situation in which if there is


a illegal access to remove a data item from
the empty stack is called “underflow”. This
situation can be avoided by using the
function empty(s)

Overflow: It is a situation in which if there is a


illegal access to insert a data item to a stack
when it is full, referred as “overflow”.

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Implementation: Stack Representation
Stack is a ordered collection of items, when
ever a problem solution calls for the use of
stack, it is generally implemented by an
array, where array is also a collection of data
items.

Both Stack & Array are different. The number


of elements in an array is fixed and It is
assigned by its declaration. But the stack is
referred as dynamic structure whose size is
constantly changing as items are pushed or
poped.

Stack
Implementation: Stack Representation
Array can not be a stack but its a home of a
stack. i.e., Array can be used to manipulate
the stack operation where array is been
declared with large enough size of the stack.

So, during the execution of program, the


stack can perform its operations with in the
space reserved for it by array.

One end of the array is fixed as a bottom of


stack where top of the stack constantly shifts
the element as per the operations

10

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Implementation: Stack Representation
Assume the problem is implemented using
an Array.

A stack in C++ can be declared as “class”,


which can hold 2 objects
1. An array to hold the elements of the stack
2. An integer to indicate the position of the
current stack top.

Stack
Implementation: Stack Representation
It can be represented as

#define size 10
class stack{
int a[size];
int top;
public:
stack(){
top=-1;
}
void push(int);
int pop();
};

11

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Implementation: Stack Representation
Implementing PUSH operation

void push(int data){


if(s.top==size){
cout<<“Stack is Full !”;
} else{
s.top++;
s.a[s.top]=data;
}
}

Stack
Implementation: Stack Representation
Implementing PUSH operation Ex.: 10,20,30

10
20 30

top
30
top
20 20
top
top 10 10 10
Empty Stack Top=0
Top=1
Top = -1
Top=3

12

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack
Implementation: Stack Representation – pop()

void pop(){
if(s.top==0){
cout<<“\n\dStack is Empty !”);
} else{
item=s.a[top];
s.top--;
}
}

Stack
Implementation: Stack Representation – pop()

30 20 10

top
30
top
20 20
top
10 10 10 top
Empty Stack Empty Stack
Empty Stack Empty Stack
Top=1 Top = 0
Top=3 Top=2

13

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Key points to be remembered
It is a linear data structure in which
insertions takes place at one end called
“rear” & deletions takes place at other end
called “front”

Queue is an ordered collection of items into


which all insertions take place at one end
and all deletions take place at the opposite
end

FIFO (First In First Out)

Queue
Queue Operations
Insertion (enqueue)
Deletion (dequeue)
Empty

14

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Key points to be remembered
Assume a Queue is implemented using an
array with the data items A, B & C. Queue can
be represented as:

rear

A B C

front

Queue
Queue Operations
Insertion
It is the operation that is used to insert a
data item at the “rear” end of a Queue

Deletion
It is the operation which is used to remove
the data item from the “front” end of
Queue
Empty
This function is used to assess the empty
state of the queue. It returns either true or
false

15

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Queue Application
Job Scheduling Techniques

Note
With reference to the queue definition, there
is no upper limit specified. It says about the
maximum number of data elements that
queue can hold

Queue
Implementation
Can be done by 2 ways
Arrays
Pointers

Note
While representing Queue using array or
linked list, it needs two variables namely
“rear” and “front” to hold the position of last
and first element of Queue

16

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Implementation
Issues with an Array
These conditions will occur if a Queue is
implemented using an array

Underflow: It is a situation in which if there


is a illegal access to remove a data item
from the empty queue is called
“underflow”. This situation can be avoided
by using the function empty(q)

Overflow: It is a situation in which if there


is a illegal access to insert a data item to a
queue when it is full, referred as
“overflow”.

Queue
Implementation: Queue Representation
Assume the problem is implemented using
an Array.

A Queue in C++ can be declared as “class”,


which can hold 2 objects
1. An array to hold the elements of the queue
2. An integers to indicate the position of the
current queue rear and fron.

17

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Implementation: Queue Representation
It can be represented as

#define size 10
class queue{
int a[size];
int rear, front;
public:
queue(){
rear=-1; front=0;
}
void enqueue(int);
int dequeue();
};

Queue
Implementation: Queue Representation
Implementing Insert operation

void enqueue(int x){


if(rear==size-1){
cout<<“Queue is Full !”;
} else{
rear++;
a[q.rear]=x;
}
}

18

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Implementation: Queue Representation
Implementing Delete operation

void dequeue(){
if(rear<front || front ==-1){
cout<<“Queue is Empty !”;
} else{
int rem;
rem=a[front];
front++;
cout<<“Data is removed”;
}
}

Queue
Example
Assume you want to insert data items 10, 20,
30 & 40 to a Queue. The schematic
representation of Queue during insertion
operation can be pictured as:
Array 10 20

10

r f f r

Initial Stage front=0


front=0 rear=0
rear=-1

19

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
40
Example
Array 30 10 20 30
10 20
f r

f r front=0 front=0
rear=1 rear=2

50

10 20 30 40 Overflow situation occurs

front=0
f rear=3 r front=0
rear=4

Queue
Deletion
Assume you have the data items 10, 20, 30 &
40 stored in a Queue. The schematic
representation of Queue during deletion
10 operation can be pictured as:
Array
20
20 30 40
30 40
30
f r
f r 40

fr

20

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Stack and Queue
Laboratory

class definition
class definition
enqueue
push
dequeue
pop
display
display
empty
empty
full
full

use switch case to manipulate operations from


main()

Stack & Queue using Pointers


Key points to be remembered
With reference to basic operations of Stack
and Queue, Both are a Linear list.

They will let you to:


Add the element to a list
Remove an element from a list

But both operations are happening at specific location

Stack - top Queue – rear & front

21

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Applications of Stack
Key terms to be remembered
System Stack
Evaluation of an Expression – 3 types
Evaluation of Infix expression
Evaluation of Postfix expression (Reverse
Polish)
Evaluation of Prefix expression (Polish)
Towers of Hanoi Puzzle
Checking Balanced Parenthesis from the
given expression

System Stack
Key terms to be remembered
It is used by a program at run time to
process function calls

Whenever a function is invoked, a program


creates a structure & places it on the top of
the system stack

This invoked function has the pointer to the


previous stack frame & return address

And previous stack frame has a pointer that


points to the invoking function

22

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
System Stack
Key terms to be remembered
Since only one function can be executed at
any given time, the function which is in the
top of the stack is chosen.

If the function invokes the other function,


then the local variables and the parameters
of the invoking function will be added to its
stack frame.

A new stack frame will be created for the


invoked function & placed it on the top of the
stack

System Stack
Key terms to be remembered
And previous stack frame has a pointer that
points to the invoking function

When this function terminates, then the


current stack frame for invoked function will
be removed from the top of the stack & the
old invoked function will again settle on the
top of stack

23

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
System Stack
Key terms to be remembered
For ex: consider a program. Assume a main
function invokes a function “m1”
The size of stack before & after the
invoking of function “m1” can be pictured
as:

fp
Prev. frame pointer
Return address m1
Local variables
fp
Prev. frame pointer Prev. frame pointer
Return address main Return address main

Figure 1 Figure 2

Expression Evaluations
Key terms to be remembered
For evaluating expressions, Stack is a
suitable data structure.

What is an expression?

24

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Key terms to be remembered
Evaluation of Infix expression
Evaluation of Postfix expression
Evaluation of Prefix expression

Remember !!!
Expression Evaluations
Infix Expression
It is a usual algebraic expression / notation
where a arithmetic operator appears between
2 operands.

Has to consider “operator precedence” for


performing the desired operation on an
expression

25

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Operator Precedence
It says order of execution of an expression
Precedence
Operator Operation Associativity
level
[] Array element reference Left to right
1
() Function invocation Right to left

++ Increment
- Unary minus
-- Decrement Left to right 2
! Logical negation
~ One’s complement

Expression Evaluations
Operator Precedence
It says order of execution of an expression
Precedence
Operator Operation Associativity
level
% Modulus
* Multiplication 3
/ Division
+ Addition
Left to right 4
- Subtraction
>> Right shift
<< Left shift 5
>>> Right shift with zero fill

26

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Operator Precedence
It says order of execution of an expression

Precedence
Operator Operation Associativity
level
> Greater than
6
>= Greater than or equal to

< Less than


<= Less than or equal to Left to right

Instanceof Type comparison


== Equality
7
!= inequality

Expression Evaluations
Infix Expression
This expression may require parenthesis to
specify a desired order of operations

Example:
consider an expression “A/B+C”. In this
expression, division will occur first

If we need addition to occur first, the


expression must be parenthesized i.e.,
A/(B+C)

27

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Postfix Expression (Reverse Polish)
Here, the need of parenthesis is eliminated
because the operator is placed directly after
the operands.

Example
An expression “A/B+C” can be written as
“AB/C+” in postfix form

“A/(B+C)” can be written as “ABC+/”

Expression Evaluations
Prefix Expression (Polish)
Here, the need of parenthesis is eliminated
because the operator is placed directly
before the operands.

Example
An expression “A/B+C” can be written as
“+/ABC” in prefix form

“A/(B+C)” can be written as “/A+BC”

28

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations

Infix Postfix Prefix


A+B AB+ +AB
A+B-C AB+C- -+ABC
(A+B)*(C-D) AB+CD-* *+AB-CD
A$B*C-D+E/F/(G+H) AB$C*D-EF/GH+/+ +-*$ABCD//EF+GH

((A+B)*C-(D-E))$(F+G) AB+C*DE—FG+$ $-*+ABC-DE+FG

A-B/(C*D$E) ABCDE$*/- -A/B*C$DE

Expression Evaluations
Evaluation of Postfix Expression
Has 2 steps
Convert the given infix expression into
postfix expression
Evaluate the postfix expression

29

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Infix to Postfix conversion process
Completely parenthesize the given infix
expression to specify the order of all
operations

Move each operator to the space held by its


corresponding right parenthesis

Remove all parenthesis

Expression Evaluations
Infix to Postfix conversion process
To parenthesis an expression, there is a
level of precedence
Level Operator Symbol

Highest Exponentiation ^
Next highest Multiplication *
Division /
Lowest Addition +
Substraction -

30

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Infix to Postfix conversion process
For instance, consider an example of
expression

A/B^C+D*E-A*C

Completely parenthesizing the expression


yields

(((A / (B ^ C)) + (D * E)) – (A * C))

Expression Evaluations
Infix to Postfix conversion process
Moving each operator to its corresponding
right parenthesis then we obtain:

( ( (A / (B ^ C) ) + (D * E) ) – (A * C) )

Completely removing all parenthesis we left


with

ABC^/ DE*+ AC*-

31

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Infix to Postfix conversion process
Example
1) 4.99 * 1.06 + 5.99 + 6.99 * 1.06
2) A / B ^ C + D * E - A * C
3) ( ( A * B ) + ( C - ( D / E ) ) )
4) A + B * C + ( D * E + F ) * G
5) A + (B * C - ( D / E î F ) * G ) * H

Expression Evaluations
Infix to Postfix conversion process (Algorithm)
1. Scan the expression from left to right
2. If a left parenthesis “(” is encountered, push
it onto the stack
3. If a operand is encountered, write it to the
output
4. If an operator is encountered, push it onto
the stack
5. If a right parenthesis is encountered, then
repeatedly POP from the stack & add it to the
output until a corresponding left parenthesis
is encountered – remove the left parenthesis
(do not add in the output)

32

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Infix to Postfix conversion process
Example:
4.99 * 1.06 + 5.99 + 6.99 * 1.06

Solution: First parenthesis the given


expression to specify order of operations

Create a table with 3 columns & execute the procedure


to get a final postfix expression
Scanned Symbol Stack Postfix Expression
? ? ?

Expression Evaluations
Evaluation of Postfix Expression
Computing the result of the given Postfix
expression

33

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluation of Postfix Expression (Algorithm)
1. Read / scan the Postfix expression from left
to right
2. If an element is an operand, push that
element onto the stack
3. If an element is an operator:
a) POP 2 operands from the stack (POP one
operand in case of NOT operator)
b) Evaluate the expression formed by 2
operands & the operator
c) PUSH the result of the expression onto the
stack

Expression Evaluations
Evaluation of Postfix Expression (Algorithm)
4. If no more elements POP the result else
continue the process from step 1.

34

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluation of Postfix Expression
1. Evaluate the postfix expression “AB+C*D/” if
A=2,B=3, C=4 and D=5 starting from left to
right

Expression Evaluations
Solution AB+C*D/
1. First element is an operand “A”, PUSH “A”
into stack

TOP

2. Second element is an operand “B”, PUSH


“B” into the stack
TOP

B
A

35

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Solution
3. Next element is an operator “+” then POP 2
elements from the stack i.e., B & A and
evaluate the expression

POP B POP A

TOP
TOP
B
TOP
A A
Stack is empty
Evaluate the expression after POP then push the result onto the stack

Expression Evaluations
Solution
Evaluating = A + B
=2+3
=5
4. PUSH the result onto the stack

PUSH 5

TOP
TOP
5

Stack is empty

36

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Solution
5. Next element is an operand “C”, PUSH “C”
into the stack

TOP
TOP
C
5 5

Expression Evaluations
Solution
6. Next element is an operator “*” then POP 2
elements from the stack i.e., C & 5 and
evaluate the expression

POP C POP 5

TOP
TOP
C TOP
5 5
Stack is empty

37

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Solution
Evaluating = 5 * C
= 5 * 4 (C = 4)
= 20
7. PUSH the result onto the stack

PUSH 20

TOP
TOP
20

Stack is empty

Expression Evaluations
Solution
8. Next element is an operand “D”, PUSH “D”
into the stack

TOP
TOP
D
20 20

38

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Solution
9. Next element is an operator “/” then POP 2
elements from the stack i.e., D & 20 and
evaluate the expression

POP D POP 20

TOP
TOP
D TOP
20 20
Stack is empty

Evaluate the expression after POP then push the result onto the stack

Expression Evaluations
Solution
Evaluating = 20 / D
= 20 / 5 (D = 5)
=4
10. PUSH the result onto the stack

PUSH 4

TOP
TOP
4

Stack is empty

39

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Solution
11. No more elements in the input of expression
so POP the element & display it as a result

POP 4

TOP

Evaluated result of given POSTFIX expression is = 4

Expression Evaluations
Evaluation of Postfix Expression
2. Evaluate the postfix expression “6 5 2 3 +
8 * + 3 + *” starting from left to right

DO IT YOURSELF?

40

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Infix to Prefix conversion process (Algorithm)
1. Scan the expression from right to left
2. If a right parenthesis “)” is encountered,
push it onto the stack
3. If a operand is encountered, write it to the
output
4. If an operator is encountered, push it onto
the stack
5. If a left parenthesis is encountered, then
repeatedly POP from the stack & add it to the
output until a right parenthesis is
encountered – remove the right parenthesis
(do not add in the output)

Expression Evaluations
Infix to Prefix conversion process
Example:
4.99 * 1.06 + 5.99 + 6.99 * 1.06

Solution: First parenthesis the given


expression to specify order of operations

Create a table with 3 columns & execute the procedure


to get a final prefix expression
Scanned Symbol Stack Prefix Expression
? ? ?

41

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Infix to Prefix conversion process
Example:
A $ B * C - D + E / F / ( G + G)

Solution: First parenthesis the given


expression to specify order of operations

((((A $ B) * C) - D) + ((E / F) / ( G + G)))

DO IT YOURSELF?

Expression Evaluations
Evaluation of Prefix Expression
Computing the result of the given Prefix
expression

42

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
1. Read / scan the Postfix expression from right
to left
2. If an element is an operand, push that
element onto the stack
3. If an element is an operator:
a) POP 2 operands from the stack (POP one
operand in case of NOT operator)
b) Evaluate the expression formed by 2
operands & the operator
c) PUSH the result of the expression onto the
stack
4. If no more elements POP the result else
continue the process from step 1.

Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
1. Evaluate the prefix expression “+A*B+CD” if
A=2,B=3, C=4 and D=5 starting from right to
left

43

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
+A*B+CD
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
1. First element is an operand “D”, PUSH “D”
into stack

TOP

2. Second element is an operand “C”, PUSH


“C” into the stack
TOP

C
D

+A*B+CD
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
3. Next element is an operator “+” then POP 2
elements from the stack i.e., B & A and
evaluate the expression

POP C POP D

TOP
TOP
C TOP
D D
Stack is empty

Evaluate the expression after POP then push the result onto the stack

44

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
Solution:
Evaluating = C + D
= 4 + 5 [C = 4; D = 5]
=9
4. PUSH the result onto the stack

PUSH 9

TOP
TOP
9

Stack is empty

+A*B+CD Expression Evaluations


Evaluation of Prefix Expression (Algorithm)
5. Next element is an operand “B”, PUSH “C”
into the stack

TOP
TOP
B
9 9

45

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
6. Next element is an operator “*” then POP 2
elements from the stack i.e., B & 9 and
evaluate the expression

POP B POP 9

TOP
TOP
B TOP
9 9
Stack is empty

Evaluate the expression after POP then push the result onto the stack

Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
Evaluating = 9 * B
= 9 * 3 (B = 3)
= 27
7. PUSH the result onto the stack

PUSH 27

TOP
TOP
27

Stack is empty

46

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
+A*B+CD
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
8. Next element is an operand “A”, PUSH “A”
into the stack

TOP
TOP
A
27 27

Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
9. Next element is an operator “+” then POP 2
elements from the stack i.e., A & 27 and
evaluate the expression

POP A POP 27

TOP
TOP
A TOP
27 27
Stack is empty

Evaluate the expression after POP then push the result onto the stack

47

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
Evaluating = 27 + A
= 27 + 2 (A = 2)
= 29
10. PUSH the result onto the stack

PUSH 29

TOP
TOP
29

Stack is empty

Expression Evaluations
Evaluation of Prefix Expression (Algorithm)
11. No more elements in the input of expression
so POP the element & display it as a result

POP 4

TOP

29

Evaluated result of given PREFIX expression is = 29

48

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Expression Evaluations
Evaluate prefix expression
Example
1) 4.99 * 1.06 + 5.99 + 6.99 * 1.06
2) A / B ^ C + D * E - A * C

Checking Balanced Parenthesis


Key terms to be remembered
Most common mistake frequently made by
the programmer is unbalance of parenthesis

For correct representation of an expression,


the following precautions must be taken.
1. There must be equal number of left & right
parenthesis

2. Each left parenthesis must be balanced by


its corresponding right parenthesis

49

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Checking Balanced Parenthesis
Algorithm
1. Scan the given expression from left to right

2. If the opening parenthesis is found, PUSH it


into the stack

3. When a closing parenthesis is found, then


POP the corresponding left open parenthesis
from stack & it is tested

4. If the opening and closing parenthesis


match, then the program will continue else
the given string is invalid

Checking Balanced Parenthesis


Key terms to be remembered
When the end of string “#” is found, then the
stack must be empty

If the stack contains elements, it means there


is some opening parenthesis that had not
been closed

50

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Checking Balanced Parenthesis
Problems
Consider the following expressions, check
whether the given expressions are balanced
or not?

1. {p+(q-[m+n])*j-[(x+y)]}
2. ( p + ( q – ( m + n ) ) * j – ( ( x + y ) ) ) / ( j – k - ( - k ( 1 –n ) ) )

Checking Balanced Parenthesis


Solution
Consider the following expression

“{ p + ( q - [ m + n ] ) * j - [ ( x + y ) ] }”

Solution: As a initial step, write the


expression with end string “#” for the
purpose of problem solving

51

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Checking Balanced Parenthesis
{p+(q-[m+n])*j-[(x+y)]}
Solution

PUSH { PUSH (

TOP
TOP
TOP (
{ TOP {

Stack is empty
PUSH [

TOP
[
(
{

Checking Balanced Parenthesis


{p+(q-[m+n])*j-[(x+y)]}
Solution
Next symbol is “]”, then POP its
corresponding “[” symbol where it matches

POP [

TOP

(
{

52

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Checking Balanced Parenthesis
{p+(q-[m+n])*j-[(x+y)]}
Solution
Next symbol is “)”, then POP its
corresponding “(” symbol where it matches

POP (

TOP

Checking Balanced Parenthesis


{p+(q-[m+n])*j-[(x+y)]}
Solution
Next symbol is “[” & “(”, then PUSH it onto
the stack

PUSH (
PUSH [

TOP
TOP
(
[ [
{ {

53

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Checking Balanced Parenthesis
{p+(q-[m+n])*j-[(x+y)]}
Solution
Next symbol is “)”, then POP its
corresponding “(” symbol where it matches

POP (

TOP
[
{

Checking Balanced Parenthesis


{p+(q-[m+n])*j-[(x+y)]}
Solution
Next symbol is “]”, then POP its
corresponding “[” symbol where it matches

POP [

TOP

54

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Checking Balanced Parenthesis
Solution
Next symbol is “}”, then POP its
corresponding “{” symbol where it matches

POP {

TOP

Checking Balanced Parenthesis


Problems
Consider the following expressions, check
whether the given expressions are balanced
or not?

( p + ( q – ( m + n ) ) * j – ( ( x + y ) ) ) / ( j – k - ( - k ( 1 –n ) ) )

DO IT YOURSELF?

55

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Key terms to be remembered
Queue
Queue Types

Queue
Key points to be remembered
It is a linear data structure in which
insertions takes place at one end called
“rear” & deletions takes place at other end
called “front”

Queue is an ordered collection of items into


which all insertions take place at one end
and all deletions take place at the opposite
end

FIFO (First In First Out)

56

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue
Key terms to be remembered
3 types
1. Circular Queue
2. Deque
3. Priority Queue

Circular Queue
Key terms to be remembered
In this Queue,
First element is stored immediately after
the last element

If the last location of a queue is occupied,


then the new element can be inserted at
the first memory location of queue, if it is
free.

Circular queue overcomes the limitation of


simple queue by utilizing the entire space

57

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Circular Queue
Key terms to be remembered
Front end of the queue always points to the
first element of the queue

If the values of front & rear are equal then the


queue is empty

The values of front & rear pointers can only


be increased / decreased after insertion /
deletion operation

Circular Queue
Key terms to be remembered
front

Q[0] Q[0]
Q[5] Q[5]
10

Q[4] Q[1] Q[4] 20 Q[1]

30
Q[3] Q[2] Q[3] Q[2]

Empty Circular Queue


rear

58

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Circular Queue
Key terms to be remembered
To perform the insertion, the position of the
element to be inserted can be calculated by
the relation

newrear = ( rear + 1 ) % maxsize

To perform deletion, the position of front


pointer is calculated using the relation

value = queue[front]
front = (front + 1) % maxsize

Circular Queue
Routine: Insertion

void insert(int item){


int newrear = (rear+1)%maxsize;
if(front==newrear){
printf(“Queue is full”);
}
else{
q[newrear]=item;
rear=newrear;
}
}

59

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Circular Queue
Routine: Deletion

void delete(){
if(front==rear){
printf(“Queue is empty”);
}
else{
front = (front + 1) % maxsize
item=q[front];
}
}

Dequeue
Key terms to be remembered
Referred as “Double Ended Queue”

It is a linear data structure where data


elements can be added or removed at either
end but not in the middle

60

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Dequeue
2 variations of Dequeue
1. Input restricted deque
2. Output restricted deque

Dequeue
Key terms to be remembered
1. Input restricted deque
It is a “deque” which allows insertion at
only one end of the list but allows
deletions at both ends of the list

2. Output restricted deque


It is a “deque” which allows deletion at
only one end of the list but allows
insertions at both ends of the list

61

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Priority Queue
Key terms to be remembered
Prehistory
In stack and Queue, the date elements are
inserted in the sequence order, where by
deletion on Stack / Queue concentrated on
any one of its ends.

These structures do not follow the natural


or intrinsic order of elements.

Priority Queue
Key terms to be remembered
Synonym
It is a data structure in which elements are
stored in natural order or intrinsic order

Example:
Arrangement of student list based on rank
or age

2 Types
1. Ascending PQ
2. Descending PQ

62

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Ascending Priority Queue
Key terms to be remembered
It is a collection of data items into which
items can be inserted arbitrarily and from
which only smallest item can be removed

Functions used in APQ


pqinsert(apq,x) – function used to insert a
data item “x” to the ascending priority
queue “apq”
pqmindelete(apq) – function used to delete
the minimum element from apq and
returns its value

Descending Priority Queue


Key terms to be remembered
It is a collection of data items into which
items can be inserted arbitrarily and from
which only largest item can be removed

Functions used in DPQ


pqinsert(dpq,x) – function used to insert a
data item “x” to the ascending priority
queue “apq”
pqmaxdelete(apq) – function used to
delete the largest element from dpq and
returns its value

63

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Priority Queue
Implementation
Insertion and deletion operations of both
stack and queue involves in accessing single
element of the array. This is not possible in
Priority Queue

For example, consider you have “n”


elements in Ascending Priority Queue

Priority Queue
Implementation
When there is a attempt to remove an
element from a APQ, there are 2 issues must
be considered: Use pqmindelete(apq)
1. To locate smallest element, every element
of an array must be examined. So, deletion
operation requires accessing of all the
elements in PQ
2. How an element situated at middle of array
can be removed?
Stack and Queue do not require searching,
where as PQ requires searching for the
element to be deleted and remove the
element in the middle of array

64

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Priority Queue
Implementation
After a data item is deleted, an “empty
indicator” can be placed in that position to
indicate the empty state

Insertion operation is modified to insert a


new data item in the first empty position.

There by insertion involves in accessing


every element in an array up to the first
empty position. Finally this process yields
the reduced efficiency

Priority Queue
Implementation
Shifting of all elements?
After the deletion is made, all other
elements are shifted to its prior position.
Insertion becomes unchanged. But
deletion becomes inefficient

65

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]
Queue Applications
Key points to be remembered
“Queues” are used for any situation where
you want to efficiently maintain a First-in-first
out order on some entities.

These situations arise literally in every type


of software development
Priority queue implementation
Batch processing in an operating system
[CPU or Disk scheduling]
Simulation
Computer networks
Queuing theory

66

Dr.A.Thomas Paul Roy, Professor, CSE Department, PSNACET, Dindigul. Email: [email protected]

You might also like