SlideShare a Scribd company logo
Data Structures & Algorithm
CSC-102
Lecture 3
Circular Link List
&
Stack
Lecturer: Syeda Nazia Ashraf 1
Circularly-linked lists
▪ The next field in the last node in a singly-linked
list is set to NULL.
▪ Moving along a singly-linked list has to be done
in a watchful manner.
▪ Doubly-linked lists have two NULL pointers:
prev in the first node and next in the last node.
▪ A way around this potential hazard is to link the
last node with the first node in the list to create
a circularly-linked list.
2
Cicularly Linked List
▪ Two views of a circularly linked list:
2 6 8 7 1
head
current
size=5
2
8
7
1
head
current
size=5
6
3
4
Building Circular List
5
6
Search B
Search A
Search C (NOT
THERE)
Search E (BIGGER
THAN ANY IN THE
LIST)
7
Insertion in
Middle of
Circular List
Insertion to
Front of
Circular List
Insertion to End
of Circular List
Insertion in Empty
Circular List
8
Deletion from
Middle of
Circular List
Deletion of smallest
item of Circular List
Deletion of only
item in Circular
List
Deletion of largest
item in Circular List
Deletion of First node in Singly Circular
List
9
Deletion of Last node in Singly Circular
List
10
Josephus Problem
▪ A case where circularly linked list comes in
handy is the solution of the Josephus Problem.
▪ Consider there are 10 persons. They would like
to choose a leader.
▪ The way they decide is that all 10 sit in a circle.
▪ They start a count with person 1 and go in
clockwise direction and skip 3. Person 4
reached is eliminated.
▪ The count starts with the fifth and the next
person to go is the fourth in count.
▪ Eventually, a single person remains.
11
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
12
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
13
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
14
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
15
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
16
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
17
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
18
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
19
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
20
Josephus Problem
▪ N=10, M=3
9
8
7
6
5
4
3
2
1
10
eliminated
21
STACKS, QUEUES, RECURSION
Introduction
The linear lists and linear arrays – allowed one to
insert and delete elements at any place in the list
•At the beginning
•At the end, or
•In the middle
To restrict insertion and deletions so that they
can take place only at the beginning, or at the
end of the list, not in the middle.
Two of the data structures that are useful are:
•Stacks
•Queue
22
STACK
• A stack is an abstract data type in which items may be
added or removed only at one end.
• An item may be added or removed only from the TOP of
any stacks.
• This means, in particular that the last item to be added
to stack is the first
item to be removed.
• Stacks are called Last-in-first-out (LIFO) Lists.
• STACKS are also called “PILES” AND “PUSH- DOWN”
23
24
• A stack stores items one on top of another. When a new item
comes in, we place it on the top of the stack and when we want to
remove an item, we take the top one from the stack. Stacks are
used for many applications in computer science such as syntax
parsing, memory management, reversing data, backtracking, etc..
• The everyday examples of such a structure are:
• Stack of dishes / trays
• Stack of pennies
• Stack of boxes
• Stack of folded towels / shirts
STACK
STACKS
A stack is a list of elements in which an element may be inserted
or deleted only at one end, called the “TOS” of the stack.
This means that elements are deleted from a stack in the reverse
order of that in which they were inserted into the stack.
Two basic operations associated with stacks
•PUSH is the term to insert an element into a stack
•POP is the item to delete an element from a stack
Example
Suppose the following 6 elements are pushes in order onto an
empty stack
AAA, BBB, CCC, DDD, EEE, FFF
25
26
Stack Operations
push(2)
top 2
push(5)
top
2
5
push(7)
top
2
5
7
push(1)
top
2
5
7
1
1 pop()
top
2
5
7
push(21)
top
2
5
7
21
21 pop()
top
2
5
7
7 pop()
2
5
top
5 pop()
2
top
27
POSTPONED DECISIONS
Stacks are frequently used to indicate the order of the processing of data when certain
steps of the processing must be postponed until other conditions are fulfilled.
Suppose we have three procedures in a project A,B, C
ARRAY REPRESENTATION OF STACKS
STACKS may be represented by means of a linear array.
•Each of our STACKS will be maintained by linear array STACKS,
•A pointer variable TOS which contains the location of the top element of the stack,
•Variable MAXSTK, which gives the maximum number of elements that, can be held by the
stack.
The Condition
TOP =0 or TOP= NULL indicate that stack is empty
XXX YYY ZZZ
1 2 3 4 5 6 7 8
Top=3 MAXSTK
=8
Stack has 3 elements => since TOP =3
There is room for 5 more items since MAXSTK =8
d e f
28
Real world examples: Stacks
• Browser history
• Interrupts
• Blog posts
Real world examples: Stacks
• Undo function
• To do lists
Stack Implementation: Array
• Worst case for insertion and deletion from
an array when insert and delete from the
beginning: shift elements to the left.
• Best case for insert and delete is at the
end of the array – no need to shift any
elements.
• Implement push( ) and pop( ) by inserting
and deleting at the end of an array.
31
Stack using an Array
top
2
5
7
1
2 5 7 1
0 1 3
2 4
top = 3
32
Stack using an Array
• A quick examination shows that all five
operations take constant time.
• In case of an array, it is possible that the
array may “fill-up” if we push enough
elements.
• Have a boolean function IsFull() which
returns true is stack (array) is full, false
otherwise.
• We would call this function before calling
push(x).
33
Stack Using Linked List
• We can avoid the size limitation of a stack
implemented with an array by using a
linked list to hold the stack elements.
• As with array, however, we need to decide
where to insert elements in the list and
where to delete them so that push and pop
will run the fastest.
34
Stack Using Linked List
• For a singly-linked list, insert at start or end
takes constant time using the head and current
pointers respectively.
• Removing an element at the start is constant
time but removal at the end required traversing
the list to the node one before the last.
• Make sense to place stack elements at the start
of the list because insert and removal are
constant time.
35
Stack Using Linked List
• No need for the current pointer; head is enough.
top
2
5
7
1
1 7 5 2
head
36
Stack Operation: List
top
2
5
7
1 7 5 2
head
37
Stack Operation: List
top
2
5
7
9
7 5 2
head
push(9)
9
newNode
38
Stack: Array or List
• Since both implementations support stack
operations in constant time, any reason to
choose one over the other?
• Allocating and deallocating memory for list
nodes does take more time than preallocated
array.
• List uses only as much memory as required by
the nodes; array requires allocation ahead of
time.
• List pointers (head, next) require extra memory.
• Array has an upper limit; List is limited by
dynamic memory allocation.
39
40
CreateStack() Pre-conditions: none
Post-conditions: S is defined and empty
Inputs: no inputs required
Outputs: S - a stack has been created
Algorithm: stack is initialised.
DestroyStack() Pre-conditions: none
Post-conditions: S is undefined. All resources (eg memory) allocated to S have been released.
No stack operation can be performed on S.
Inputs: the stack
Outputs: an empty stack
Algorithm: Removes all elements from Stack, leaving the stack empty. stack is re-initialised
Pop(element) Pre-conditions: stack is not empty
Post-conditions: the top element has been removed from the stack
Inputs: the stack
Outputs: the changed stack, ie top element, has been removed
Algorithm: remove the top element of the stack; give a copy of the element back to the user
Push(element) Pre-conditions: the stack exists, element is of appropriate type
Post-conditions: Element is put onto the top of the stack.
Inputs: a stack and an element
Outputs: a changed stack
Algorithm: insert the element into the stack
IsEmpty() Pre-conditions: a stack exists
Post-conditions: returns true if empty false otherwise.
Inputs: a stack
Outputs: boolean value
Algorithm: check initial status of the stack and report whether empty or not.
Stack Operations
PUSH
In executing the procedure PUSH, one must first test
whether there is ROOM in stack for the new item, if not,
then we have the condition known as overflow.
PUSH (STACK, TOS, MAXSTK, ITEM)
This procedure pushes an ITEM onto a stack.
Algorithm
1. [Stack already filled?]
If TOS= MAXSTK, then: Print OVERFLOW and Return
2. Set TOS := TOS+1. [Increasing TOS by 1]
3. Set Stack[TOS]:= ITEM . [Insert ITEM in New TOS
position ]
4. Return
41
POP
In executing POP, one must first test whether there is an
element in stack to be deleted, if not, then we have the
condition known as underflow.
POP (STACK, TOS, ITEM)
This procedure deletes the top element of STACK and assigns it to
the variable ITEM.
Algorithm
1. [Stack has an item to be removed]
If TOS=0, then: Print: UNDER FLOW & Return.
2. Set ITEM := STACK[TOS]. [Assigns TOS element to ITEM]
3 Set TOS= TOS-1. [ Decrease TOS by 1]
4. Return
Example:
Consider the stack, the operation PUSH (STACK, WWW)
1. Since TOP =3 control is transferred to Step 2.
2. Top=3+1=4
3. Stack[Top]= Stack[4]=WWW 42
43
44
Minimizing Overflow:
Essential difference between underflow and overflow in dealing stacks
Underflow Depends relatively upon the given algorithm and given input data
and hence there is no direct control by the programmer
Overflow Depends upon the arbitrary choice of the programmer for the
amount of memory space reserved for each stack, and this choice
does influence the number of times overflow may occur
Arithmetic Expressions:
Binary operations in an equation may have different levels of precedence.
The following three levels of precedence:
Highest: Exponentiation ()
Next Highest: Multiplication (*) and Division (/)
Lowest: Addition (+) and subtraction (-)
45
INFIX PREFIX
(A+B)*C [+AB]*C =*+ABC
A+(B*C) A+[*BC]=+A*BC
(A+B)/(C-D) [+AB]/[-CD]= /+AB-CD
Use of Stack
Infix Notation:
For most common arithmetic operations, the operator symbol is placed
between its two operands,
For example:
A+B C-D E*F (G/H) +A
This is called infix notation
Polish Notation (Prefix Notation):
Polish notation refers to the notation in which the operator symbol is placed
before its two operands, for example:
+AB -CD *EF [/GH] +A=+/GHA
Some examples:
The fundamental property of POLISH (PREFIX) NOTATION is that the order in
which the operations are performed in completely determined by the positions
of the operations and operands in the expression.
One never needs parenthesis when resulting expressions in this notation.
46
Precedence of Operators
• For operators of same precedence, the
left-to-right rule applies:
A+B+C means (A+B)+C.
• For exponentiation, the right-to-left rule
applies
A  B  C means A  ( B  C )
47
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
A + ( B C * ) convert multiplication
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
A + ( B C * ) convert multiplication
A ( B C * ) + convert addition
Prefix, Infix, Postfix
• Conversion to postfix
A + ( B * C ) infix form
A + ( B C * ) convert multiplication
A ( B C * ) + convert addition
A B C * + postfix form
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
( A B + ) * C convert addition
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
( A B + ) * C convert addition
( A B + ) C * convert multiplication
Prefix, Infix, Postfix
• Conversion to postfix
(A + B ) * C infix form
( A B + ) * C convert addition
( A B + ) C * convert multiplication
A B + C * postfix form
Infix to Postfix
Infix Postfix
A + B A B +
12 + 60 – 23 12 60 + 23 –
(A + B)*(C – D ) A B + C D – *
A  B * C – D + E/F A B  C*D – E F/+
56
Reverse Polish Notation
Refers to the analogous notation in which the
operator symbol is placed after its two operands
AB+ CD- EF* GHA/+
This notation is called POSTFIX or suffix notation.
The computer usually evaluates an arithmetic
expression written in infix notation into steps:
First converts the expression to postfix notation
and
Evaluates the postfix expression
Stack is the main tool that is used to accomplish
given task.
57
Evaluating Postfix
• Each operator in a postfix expression
refers to the previous two operands.
• Each time we read an operand, we push it
on a stack.
• When we reach an operator, we pop the
two operands from the top of the stack,
apply the operator and push the result
back on the stack.
58
Evaluation of a Postfix Notation
Suppose P is an arithmetic expression written in postfix notation.
The following algorithm which uses a STACK to hold operands, evaluates P.
Algorithm:
This algorithm finds the VALUE of an arithmetic expression P written in Postfix
notation.
1. Add a right parenthesis “)” at the end of P.
[This acts as a sentinel]
2. Scan P from left to right and repeat step 3 and 4 for each element of P
until the sentinel “)”is encountered.
3. If an operand is encountered, put it in STACK.
4. If an operator X is encountered, then:
i) Remove the two top elements of STACK, where
A is the top element and
B is the next-to-top element.
ii) Evaluate B X A
iii) Place the result of (b) back on STACK.
[End of IF Structure]
[End of STEP 2 loop]
5. Set VALUE equal to the top element on STACK.
6. Exit 59
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
 7 2 49 49
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
 7 2 49 49
3 7 2 49 49,3
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
 7 2 49 49
3 7 2 49 49,3
+ 49 3 52 52
Evaluating Postfix
Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + )
Input op1 op2 value stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
 7 2 49 49
3 7 2 49 49,3
+ 49 3 52 52
)
Example:
Consider the following arithmetic expression P written in Postfix notation:
P: 5, 6, 2, +,*, 12, 4, /,-
Commas are used to separate the elements of P so that 5, 6, 2 is not interpreted as the number 562.
Symbol
Scanned
STACK
5 5
6 5,6
2 5,6,2
+ 5,8
* 40
12 40,12
4 40, 12, 4
/ 40, 3
- 37
)
Equivalent INFIX EXPRESSION is:
Q: 5* (6+2)-12/4
Parenthesis are necessary for the infix expression Q but not for the postfix expression P
First we add a right parenthesis at the end of P.
The elements are labeled from left to right
The final number in STACK, 37 which is assigned to value when the sentinel “)” is scanned is
the value of P. 77
78
Evaluation of a Prefix Notation
Suppose P is an arithmetic expression written in prefix notation.
The following algorithm which uses a STACK to hold operands, evaluates P.
Algorithm:
This algorithm finds the VALUE of an arithmetic expression P written in Prefix
notation.
1. Add a right parenthesis “(” at the end of P.
[This acts as a sentinel]
2. Scan P from right to left and repeat step 3 and 4 for each element of P
until the sentinel “(”is encountered.
3. If an operand is encountered, put it in STACK.
4. If an operator X is encountered, then:
i) Remove the two top elements of STACK, where
A is the top element and
B is the next-to-top element.
ii) Evaluate A X B
iii) Place the result of (b) back on STACK.
[End of IF Structure]
[End of STEP 2 loop]
5. Set VALUE equal to the top element on STACK.
6. Exit
79
Evaluating Prefix
(
(
80
Expression: ( +9*26
Character | Stack | Explanation
Scanned | (Front to |
| Back) |
-------------------------------------------
6 6 6 is an operand,
push to Stack
2 6 2 2 is an operand,
push to Stack
* 12 (6*2) * is an operator,
pop 6 and 2, multiply
them and push result
to Stack
9 12 9 9 is an operand, push
to Stack
+ 21 (12+9) + is an operator, pop
12 and 9 add them and
push result to Stack
(
Result: 21
Evaluating Prefix
Transforming Infix Expression into Postfix Expression
The following algorithm transforms the infix expression Q
into its equivalent postfix expression P.
The algorithm uses a STACK to temporarily hold operators
and left parentheses.
The postfix expression P will be constructed from left to
right using the operands and left parentheses.
The postfix expression P will be constructed from left to
right using the operands from Q and the operators which
are removed from STACK.
We begin by pushing a left parenthesis onto STACK and
adding right parentheses at the end of Q.
The algorithm is completed when STACK is empty.
81
Algorithm:
POLISH (Q, P)
Suppose Q is an arithmetic expression written in infix notation.
This algorithm finds the equivalent postfix expression P.
1. PUSH “(” onto STACK, and add “)” to the end of Q
2. Scan Q from left to right and repeat step 3 to step 6 for each element of Q
until the STACK is empty.
3. If an operand is encountered, add it to P
4. If a left parenthesis is encountered, push it onto STACK.
5. If an operator X is encountered then:
i) Repeatedly POP from STACK and add to P each operator (on the top
of STACK) which has the same precedence as or higher precedence
than X
ii) Add X to STACK
[END of IF Structure]
6. If a right parenthesis is encountered then:
i) Repeatedly POP from STACK and add to P each operator (on the top
of STACK) until a left parenthesis is encountered.
ii) Remove the left parenthesis. [Do not add the left parenthesis to P]
[End of IF Structure]
[End of STEP 2 loop]
7. Exit 82
83
84
85
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
+ A +
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
+ A +
B AB +
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
+ A +
B AB +
* AB + *
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
+ A +
B AB +
* AB + *
C ABC + *
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
+ A +
B AB +
* AB + *
C ABC + *
ABC * +
Converting Infix to Postfix
• Example: A + B * C
symb postfix stack
A A
+ A +
B AB +
* AB + *
C ABC + *
ABC * +
ABC * +
ASSIGNMENT 1
Convert given expression into Prefix(Polish) Notation. Write algorithm and
Symbol Table which shows status of stack.
93

More Related Content

PPT
Stacks and queues
PPT
Stacks and queue
PDF
stacks and queues
PPTX
Unit 5 linked list
PPT
Stacks, Queues, Deques
PPTX
stacks and queues
PDF
Stacks,queues,linked-list
PPT
Data structure lecture7
Stacks and queues
Stacks and queue
stacks and queues
Unit 5 linked list
Stacks, Queues, Deques
stacks and queues
Stacks,queues,linked-list
Data structure lecture7

What's hot (20)

PPT
Unit 3 stack
PPT
Stack and queue
PPTX
Stack and Queue
PDF
Module 01 Stack and Recursion
PPTX
Queue Data Structure (w/ php egs)
PPTX
Lecture 6 data structures and algorithms
PPT
Stacks queues
PDF
LEC4-DS ALGO.pdf
PPT
23 stacks-queues-deques
PDF
Stack and Queue (brief)
PPTX
Unit 4 queue
PPTX
Stacks in c++
PDF
04 stacks
PPTX
Stack and its operations
PPT
Stacks & Queues
PPTX
Linked List - Insertion & Deletion
Unit 3 stack
Stack and queue
Stack and Queue
Module 01 Stack and Recursion
Queue Data Structure (w/ php egs)
Lecture 6 data structures and algorithms
Stacks queues
LEC4-DS ALGO.pdf
23 stacks-queues-deques
Stack and Queue (brief)
Unit 4 queue
Stacks in c++
04 stacks
Stack and its operations
Stacks & Queues
Linked List - Insertion & Deletion
Ad

Similar to LEC3-DS ALGO(updated).pdf (20)

PDF
Chapter 5 Stack and Queue.pdf
PPT
Lecture5
PPTX
6 - STACKS in Data Structure and Algorithm.pptx
PPTX
Abscddnddmdkwkkstack implementation.pptx
PPT
The Stack in data structures .ppt
PDF
Stack push pop
PPTX
My lecture stack_queue_operation
PPTX
Lecture_5_Stack.pptx
PDF
PDF
PPTX
DSVIDEO.pptx data structure for bca and bsc cs students to higher
DOCX
Stacks in data structure
PPTX
Introduction to information about Data Structure.pptx
PPTX
STACK.pptx
PPTX
هياكلبيانات
PPTX
DS UNIT 2 PPT.pptx stack queue representations
PPTX
Stacks and queues using aaray line .pptx
PPTX
U3.stack queue
PPSX
Stacks fundamentals
PPT
unit 5 stack & queue.ppt
Chapter 5 Stack and Queue.pdf
Lecture5
6 - STACKS in Data Structure and Algorithm.pptx
Abscddnddmdkwkkstack implementation.pptx
The Stack in data structures .ppt
Stack push pop
My lecture stack_queue_operation
Lecture_5_Stack.pptx
DSVIDEO.pptx data structure for bca and bsc cs students to higher
Stacks in data structure
Introduction to information about Data Structure.pptx
STACK.pptx
هياكلبيانات
DS UNIT 2 PPT.pptx stack queue representations
Stacks and queues using aaray line .pptx
U3.stack queue
Stacks fundamentals
unit 5 stack & queue.ppt
Ad

More from MuhammadUmerIhtisham (13)

PDF
LECT 10, 11-DSALGO(Hashing).pdf
PDF
LEC 12-DSALGO-GRAPHS(final12).pdf
PDF
Lect 13, 14 (final)AVL Tree and Rotations.pdf
PDF
LEC 7-DS ALGO(expression and huffman).pdf
PDF
LEC 8-DS ALGO(heaps).pdf
PDF
LEC 5-DS ALGO(updated).pdf
PDF
LEC 6-DS ALGO(updated).pdf
PDF
lect 1-ds algo(final)_2.pdf
PDF
lect 2-DS ALGO(online).pdf
PDF
SMIU Discrete Structure Lecture 3 Section 3E.pdf
PDF
Discrete Structure Lecture #5 & 6.pdf
PDF
Discrete Structure Lecture #7 & 8.pdf
PDF
SMIU Lecture #1 & 2 Introduction to Discrete Structure and Truth Table.pdf
LECT 10, 11-DSALGO(Hashing).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
Lect 13, 14 (final)AVL Tree and Rotations.pdf
LEC 7-DS ALGO(expression and huffman).pdf
LEC 8-DS ALGO(heaps).pdf
LEC 5-DS ALGO(updated).pdf
LEC 6-DS ALGO(updated).pdf
lect 1-ds algo(final)_2.pdf
lect 2-DS ALGO(online).pdf
SMIU Discrete Structure Lecture 3 Section 3E.pdf
Discrete Structure Lecture #5 & 6.pdf
Discrete Structure Lecture #7 & 8.pdf
SMIU Lecture #1 & 2 Introduction to Discrete Structure and Truth Table.pdf

Recently uploaded (20)

PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Institutional Correction lecture only . . .
PPTX
Cell Structure & Organelles in detailed.
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Business Ethics Teaching Materials for college
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
01-Introduction-to-Information-Management.pdf
PPTX
master seminar digital applications in india
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Basic Mud Logging Guide for educational purpose
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Week 4 Term 3 Study Techniques revisited.pptx
O7-L3 Supply Chain Operations - ICLT Program
O5-L3 Freight Transport Ops (International) V1.pdf
PPH.pptx obstetrics and gynecology in nursing
human mycosis Human fungal infections are called human mycosis..pptx
Institutional Correction lecture only . . .
Cell Structure & Organelles in detailed.
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Final Presentation General Medicine 03-08-2024.pptx
Business Ethics Teaching Materials for college
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
Pharma ospi slides which help in ospi learning
Pharmacology of Heart Failure /Pharmacotherapy of CHF
01-Introduction-to-Information-Management.pdf
master seminar digital applications in india
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Basic Mud Logging Guide for educational purpose

LEC3-DS ALGO(updated).pdf

  • 1. Data Structures & Algorithm CSC-102 Lecture 3 Circular Link List & Stack Lecturer: Syeda Nazia Ashraf 1
  • 2. Circularly-linked lists ▪ The next field in the last node in a singly-linked list is set to NULL. ▪ Moving along a singly-linked list has to be done in a watchful manner. ▪ Doubly-linked lists have two NULL pointers: prev in the first node and next in the last node. ▪ A way around this potential hazard is to link the last node with the first node in the list to create a circularly-linked list. 2
  • 3. Cicularly Linked List ▪ Two views of a circularly linked list: 2 6 8 7 1 head current size=5 2 8 7 1 head current size=5 6 3
  • 5. 5
  • 6. 6 Search B Search A Search C (NOT THERE) Search E (BIGGER THAN ANY IN THE LIST)
  • 7. 7 Insertion in Middle of Circular List Insertion to Front of Circular List Insertion to End of Circular List Insertion in Empty Circular List
  • 8. 8 Deletion from Middle of Circular List Deletion of smallest item of Circular List Deletion of only item in Circular List Deletion of largest item in Circular List
  • 9. Deletion of First node in Singly Circular List 9
  • 10. Deletion of Last node in Singly Circular List 10
  • 11. Josephus Problem ▪ A case where circularly linked list comes in handy is the solution of the Josephus Problem. ▪ Consider there are 10 persons. They would like to choose a leader. ▪ The way they decide is that all 10 sit in a circle. ▪ They start a count with person 1 and go in clockwise direction and skip 3. Person 4 reached is eliminated. ▪ The count starts with the fifth and the next person to go is the fourth in count. ▪ Eventually, a single person remains. 11
  • 12. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 12
  • 13. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 13
  • 14. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 14
  • 15. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 15
  • 16. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 16
  • 17. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 17
  • 18. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 18
  • 19. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 19
  • 20. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 20
  • 21. Josephus Problem ▪ N=10, M=3 9 8 7 6 5 4 3 2 1 10 eliminated 21
  • 22. STACKS, QUEUES, RECURSION Introduction The linear lists and linear arrays – allowed one to insert and delete elements at any place in the list •At the beginning •At the end, or •In the middle To restrict insertion and deletions so that they can take place only at the beginning, or at the end of the list, not in the middle. Two of the data structures that are useful are: •Stacks •Queue 22
  • 23. STACK • A stack is an abstract data type in which items may be added or removed only at one end. • An item may be added or removed only from the TOP of any stacks. • This means, in particular that the last item to be added to stack is the first item to be removed. • Stacks are called Last-in-first-out (LIFO) Lists. • STACKS are also called “PILES” AND “PUSH- DOWN” 23
  • 24. 24 • A stack stores items one on top of another. When a new item comes in, we place it on the top of the stack and when we want to remove an item, we take the top one from the stack. Stacks are used for many applications in computer science such as syntax parsing, memory management, reversing data, backtracking, etc.. • The everyday examples of such a structure are: • Stack of dishes / trays • Stack of pennies • Stack of boxes • Stack of folded towels / shirts STACK
  • 25. STACKS A stack is a list of elements in which an element may be inserted or deleted only at one end, called the “TOS” of the stack. This means that elements are deleted from a stack in the reverse order of that in which they were inserted into the stack. Two basic operations associated with stacks •PUSH is the term to insert an element into a stack •POP is the item to delete an element from a stack Example Suppose the following 6 elements are pushes in order onto an empty stack AAA, BBB, CCC, DDD, EEE, FFF 25
  • 26. 26
  • 27. Stack Operations push(2) top 2 push(5) top 2 5 push(7) top 2 5 7 push(1) top 2 5 7 1 1 pop() top 2 5 7 push(21) top 2 5 7 21 21 pop() top 2 5 7 7 pop() 2 5 top 5 pop() 2 top 27
  • 28. POSTPONED DECISIONS Stacks are frequently used to indicate the order of the processing of data when certain steps of the processing must be postponed until other conditions are fulfilled. Suppose we have three procedures in a project A,B, C ARRAY REPRESENTATION OF STACKS STACKS may be represented by means of a linear array. •Each of our STACKS will be maintained by linear array STACKS, •A pointer variable TOS which contains the location of the top element of the stack, •Variable MAXSTK, which gives the maximum number of elements that, can be held by the stack. The Condition TOP =0 or TOP= NULL indicate that stack is empty XXX YYY ZZZ 1 2 3 4 5 6 7 8 Top=3 MAXSTK =8 Stack has 3 elements => since TOP =3 There is room for 5 more items since MAXSTK =8 d e f 28
  • 29. Real world examples: Stacks • Browser history • Interrupts • Blog posts
  • 30. Real world examples: Stacks • Undo function • To do lists
  • 31. Stack Implementation: Array • Worst case for insertion and deletion from an array when insert and delete from the beginning: shift elements to the left. • Best case for insert and delete is at the end of the array – no need to shift any elements. • Implement push( ) and pop( ) by inserting and deleting at the end of an array. 31
  • 32. Stack using an Array top 2 5 7 1 2 5 7 1 0 1 3 2 4 top = 3 32
  • 33. Stack using an Array • A quick examination shows that all five operations take constant time. • In case of an array, it is possible that the array may “fill-up” if we push enough elements. • Have a boolean function IsFull() which returns true is stack (array) is full, false otherwise. • We would call this function before calling push(x). 33
  • 34. Stack Using Linked List • We can avoid the size limitation of a stack implemented with an array by using a linked list to hold the stack elements. • As with array, however, we need to decide where to insert elements in the list and where to delete them so that push and pop will run the fastest. 34
  • 35. Stack Using Linked List • For a singly-linked list, insert at start or end takes constant time using the head and current pointers respectively. • Removing an element at the start is constant time but removal at the end required traversing the list to the node one before the last. • Make sense to place stack elements at the start of the list because insert and removal are constant time. 35
  • 36. Stack Using Linked List • No need for the current pointer; head is enough. top 2 5 7 1 1 7 5 2 head 36
  • 38. Stack Operation: List top 2 5 7 9 7 5 2 head push(9) 9 newNode 38
  • 39. Stack: Array or List • Since both implementations support stack operations in constant time, any reason to choose one over the other? • Allocating and deallocating memory for list nodes does take more time than preallocated array. • List uses only as much memory as required by the nodes; array requires allocation ahead of time. • List pointers (head, next) require extra memory. • Array has an upper limit; List is limited by dynamic memory allocation. 39
  • 40. 40 CreateStack() Pre-conditions: none Post-conditions: S is defined and empty Inputs: no inputs required Outputs: S - a stack has been created Algorithm: stack is initialised. DestroyStack() Pre-conditions: none Post-conditions: S is undefined. All resources (eg memory) allocated to S have been released. No stack operation can be performed on S. Inputs: the stack Outputs: an empty stack Algorithm: Removes all elements from Stack, leaving the stack empty. stack is re-initialised Pop(element) Pre-conditions: stack is not empty Post-conditions: the top element has been removed from the stack Inputs: the stack Outputs: the changed stack, ie top element, has been removed Algorithm: remove the top element of the stack; give a copy of the element back to the user Push(element) Pre-conditions: the stack exists, element is of appropriate type Post-conditions: Element is put onto the top of the stack. Inputs: a stack and an element Outputs: a changed stack Algorithm: insert the element into the stack IsEmpty() Pre-conditions: a stack exists Post-conditions: returns true if empty false otherwise. Inputs: a stack Outputs: boolean value Algorithm: check initial status of the stack and report whether empty or not. Stack Operations
  • 41. PUSH In executing the procedure PUSH, one must first test whether there is ROOM in stack for the new item, if not, then we have the condition known as overflow. PUSH (STACK, TOS, MAXSTK, ITEM) This procedure pushes an ITEM onto a stack. Algorithm 1. [Stack already filled?] If TOS= MAXSTK, then: Print OVERFLOW and Return 2. Set TOS := TOS+1. [Increasing TOS by 1] 3. Set Stack[TOS]:= ITEM . [Insert ITEM in New TOS position ] 4. Return 41
  • 42. POP In executing POP, one must first test whether there is an element in stack to be deleted, if not, then we have the condition known as underflow. POP (STACK, TOS, ITEM) This procedure deletes the top element of STACK and assigns it to the variable ITEM. Algorithm 1. [Stack has an item to be removed] If TOS=0, then: Print: UNDER FLOW & Return. 2. Set ITEM := STACK[TOS]. [Assigns TOS element to ITEM] 3 Set TOS= TOS-1. [ Decrease TOS by 1] 4. Return Example: Consider the stack, the operation PUSH (STACK, WWW) 1. Since TOP =3 control is transferred to Step 2. 2. Top=3+1=4 3. Stack[Top]= Stack[4]=WWW 42
  • 43. 43
  • 44. 44
  • 45. Minimizing Overflow: Essential difference between underflow and overflow in dealing stacks Underflow Depends relatively upon the given algorithm and given input data and hence there is no direct control by the programmer Overflow Depends upon the arbitrary choice of the programmer for the amount of memory space reserved for each stack, and this choice does influence the number of times overflow may occur Arithmetic Expressions: Binary operations in an equation may have different levels of precedence. The following three levels of precedence: Highest: Exponentiation () Next Highest: Multiplication (*) and Division (/) Lowest: Addition (+) and subtraction (-) 45
  • 46. INFIX PREFIX (A+B)*C [+AB]*C =*+ABC A+(B*C) A+[*BC]=+A*BC (A+B)/(C-D) [+AB]/[-CD]= /+AB-CD Use of Stack Infix Notation: For most common arithmetic operations, the operator symbol is placed between its two operands, For example: A+B C-D E*F (G/H) +A This is called infix notation Polish Notation (Prefix Notation): Polish notation refers to the notation in which the operator symbol is placed before its two operands, for example: +AB -CD *EF [/GH] +A=+/GHA Some examples: The fundamental property of POLISH (PREFIX) NOTATION is that the order in which the operations are performed in completely determined by the positions of the operations and operands in the expression. One never needs parenthesis when resulting expressions in this notation. 46
  • 47. Precedence of Operators • For operators of same precedence, the left-to-right rule applies: A+B+C means (A+B)+C. • For exponentiation, the right-to-left rule applies A  B  C means A  ( B  C ) 47
  • 48. Prefix, Infix, Postfix • Conversion to postfix A + ( B * C ) infix form
  • 49. Prefix, Infix, Postfix • Conversion to postfix A + ( B * C ) infix form A + ( B C * ) convert multiplication
  • 50. Prefix, Infix, Postfix • Conversion to postfix A + ( B * C ) infix form A + ( B C * ) convert multiplication A ( B C * ) + convert addition
  • 51. Prefix, Infix, Postfix • Conversion to postfix A + ( B * C ) infix form A + ( B C * ) convert multiplication A ( B C * ) + convert addition A B C * + postfix form
  • 52. Prefix, Infix, Postfix • Conversion to postfix (A + B ) * C infix form
  • 53. Prefix, Infix, Postfix • Conversion to postfix (A + B ) * C infix form ( A B + ) * C convert addition
  • 54. Prefix, Infix, Postfix • Conversion to postfix (A + B ) * C infix form ( A B + ) * C convert addition ( A B + ) C * convert multiplication
  • 55. Prefix, Infix, Postfix • Conversion to postfix (A + B ) * C infix form ( A B + ) * C convert addition ( A B + ) C * convert multiplication A B + C * postfix form
  • 56. Infix to Postfix Infix Postfix A + B A B + 12 + 60 – 23 12 60 + 23 – (A + B)*(C – D ) A B + C D – * A  B * C – D + E/F A B  C*D – E F/+ 56
  • 57. Reverse Polish Notation Refers to the analogous notation in which the operator symbol is placed after its two operands AB+ CD- EF* GHA/+ This notation is called POSTFIX or suffix notation. The computer usually evaluates an arithmetic expression written in infix notation into steps: First converts the expression to postfix notation and Evaluates the postfix expression Stack is the main tool that is used to accomplish given task. 57
  • 58. Evaluating Postfix • Each operator in a postfix expression refers to the previous two operands. • Each time we read an operand, we push it on a stack. • When we reach an operator, we pop the two operands from the top of the stack, apply the operator and push the result back on the stack. 58
  • 59. Evaluation of a Postfix Notation Suppose P is an arithmetic expression written in postfix notation. The following algorithm which uses a STACK to hold operands, evaluates P. Algorithm: This algorithm finds the VALUE of an arithmetic expression P written in Postfix notation. 1. Add a right parenthesis “)” at the end of P. [This acts as a sentinel] 2. Scan P from left to right and repeat step 3 and 4 for each element of P until the sentinel “)”is encountered. 3. If an operand is encountered, put it in STACK. 4. If an operator X is encountered, then: i) Remove the two top elements of STACK, where A is the top element and B is the next-to-top element. ii) Evaluate B X A iii) Place the result of (b) back on STACK. [End of IF Structure] [End of STEP 2 loop] 5. Set VALUE equal to the top element on STACK. 6. Exit 59
  • 60. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack
  • 61. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6
  • 62. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2
  • 63. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3
  • 64. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5
  • 65. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1
  • 66. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3
  • 67. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8
  • 68. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2
  • 69. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4
  • 70. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7
  • 71. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7
  • 72. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2
  • 73. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2  7 2 49 49
  • 74. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2  7 2 49 49 3 7 2 49 49,3
  • 75. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2  7 2 49 49 3 7 2 49 49,3 + 49 3 52 52
  • 76. Evaluating Postfix Evaluate 6 2 3 + - 3 8 2 / + * 2  3 + ) Input op1 op2 value stack 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2  7 2 49 49 3 7 2 49 49,3 + 49 3 52 52 )
  • 77. Example: Consider the following arithmetic expression P written in Postfix notation: P: 5, 6, 2, +,*, 12, 4, /,- Commas are used to separate the elements of P so that 5, 6, 2 is not interpreted as the number 562. Symbol Scanned STACK 5 5 6 5,6 2 5,6,2 + 5,8 * 40 12 40,12 4 40, 12, 4 / 40, 3 - 37 ) Equivalent INFIX EXPRESSION is: Q: 5* (6+2)-12/4 Parenthesis are necessary for the infix expression Q but not for the postfix expression P First we add a right parenthesis at the end of P. The elements are labeled from left to right The final number in STACK, 37 which is assigned to value when the sentinel “)” is scanned is the value of P. 77
  • 78. 78 Evaluation of a Prefix Notation Suppose P is an arithmetic expression written in prefix notation. The following algorithm which uses a STACK to hold operands, evaluates P. Algorithm: This algorithm finds the VALUE of an arithmetic expression P written in Prefix notation. 1. Add a right parenthesis “(” at the end of P. [This acts as a sentinel] 2. Scan P from right to left and repeat step 3 and 4 for each element of P until the sentinel “(”is encountered. 3. If an operand is encountered, put it in STACK. 4. If an operator X is encountered, then: i) Remove the two top elements of STACK, where A is the top element and B is the next-to-top element. ii) Evaluate A X B iii) Place the result of (b) back on STACK. [End of IF Structure] [End of STEP 2 loop] 5. Set VALUE equal to the top element on STACK. 6. Exit
  • 80. 80 Expression: ( +9*26 Character | Stack | Explanation Scanned | (Front to | | Back) | ------------------------------------------- 6 6 6 is an operand, push to Stack 2 6 2 2 is an operand, push to Stack * 12 (6*2) * is an operator, pop 6 and 2, multiply them and push result to Stack 9 12 9 9 is an operand, push to Stack + 21 (12+9) + is an operator, pop 12 and 9 add them and push result to Stack ( Result: 21 Evaluating Prefix
  • 81. Transforming Infix Expression into Postfix Expression The following algorithm transforms the infix expression Q into its equivalent postfix expression P. The algorithm uses a STACK to temporarily hold operators and left parentheses. The postfix expression P will be constructed from left to right using the operands and left parentheses. The postfix expression P will be constructed from left to right using the operands from Q and the operators which are removed from STACK. We begin by pushing a left parenthesis onto STACK and adding right parentheses at the end of Q. The algorithm is completed when STACK is empty. 81
  • 82. Algorithm: POLISH (Q, P) Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression P. 1. PUSH “(” onto STACK, and add “)” to the end of Q 2. Scan Q from left to right and repeat step 3 to step 6 for each element of Q until the STACK is empty. 3. If an operand is encountered, add it to P 4. If a left parenthesis is encountered, push it onto STACK. 5. If an operator X is encountered then: i) Repeatedly POP from STACK and add to P each operator (on the top of STACK) which has the same precedence as or higher precedence than X ii) Add X to STACK [END of IF Structure] 6. If a right parenthesis is encountered then: i) Repeatedly POP from STACK and add to P each operator (on the top of STACK) until a left parenthesis is encountered. ii) Remove the left parenthesis. [Do not add the left parenthesis to P] [End of IF Structure] [End of STEP 2 loop] 7. Exit 82
  • 83. 83
  • 84. 84
  • 85. 85
  • 86. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A
  • 87. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A + A +
  • 88. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A + A + B AB +
  • 89. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A + A + B AB + * AB + *
  • 90. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A + A + B AB + * AB + * C ABC + *
  • 91. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A + A + B AB + * AB + * C ABC + * ABC * +
  • 92. Converting Infix to Postfix • Example: A + B * C symb postfix stack A A + A + B AB + * AB + * C ABC + * ABC * + ABC * +
  • 93. ASSIGNMENT 1 Convert given expression into Prefix(Polish) Notation. Write algorithm and Symbol Table which shows status of stack. 93