0% found this document useful (0 votes)
14 views74 pages

3 Stacks Queues

Uploaded by

Govind 025
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)
14 views74 pages

3 Stacks Queues

Uploaded by

Govind 025
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/ 74

DATA STRUCTURE

DR. ACHAL KAUSHIK

10/9/2023 1
Paper Code(s): CIC-209 L P C
Paper: Data Structures 4 - 4
Marking Scheme:
1. Teachers Continuous Evaluation: 25 marks
2. Term end Theory Examinations: 75 marks
Instructions for paper setter:
1. There should be 9 questions in the term end examinations question paper.
2. The first (1st) question should be compulsory and cover the entire syllabus. This question should be objective, single line answers or short
answer type question of total 15 marks.
3. Apart from question 1 which is compulsory, rest of the paper shall consist of 4 units as per the syllabus. Every unit shall have two questions
covering the corresponding unit of the syllabus. However, the student shall be asked to attempt only one of the two questions in the unit.
Individual questions may contain upto 5 sub-parts / sub-questions. Each Unit shall have a marks weightage of 15.
4. The questions are to be framed keeping in view the learning outcomes of the course / paper. The standard / level of the questions to be asked
should be at the level of the prescribed textbook.
5. The requirement of (scientific) calculators / log-tables / data – tables may be specified if required.
Course Objectives :
1. To introduce basics of Data structures (Arrays, strings, linked list etc.)
2. To understand the concepts of Stacks, Queues and Trees, related operations and their implementation
3. To understand sets, heaps and graphs
4. To introduce various Sorting and searching Algorithms
Course Outcomes (CO)
CO 1 To be able to understand difference between structured data and data structure
CO 2 To be able to create common basic data structures and trees
CO 3 To have a knowledge of sets, heaps and graphs
CO 4 To have basic knowledge of sorting and searching algorithms
Course Outcomes (CO) to Programme Outcomes (PO) mapping (scale 1: low, 2: Medium, 3: High)
PO01 PO02 PO03 PO04 PO05 PO06 PO07 PO08 PO09 PO10 PO11 PO12

CO 1 3 2 2 2 3 - - - 2 2 2 3
CO 2 3 2 2 2 3 - - - 2 2 2 3
CO 3 3 2 2 2 3 - - - 2 2 2 3
CO 4 3 2 2 2 3 - - - 2 2 2 3
UNIT – I
Overview of data structure, Basics of Algorithm Analysis including Running Time Calculations, Abstract Data Types, Arrays, Arrays and Pointers,
Multidimensional Array, String processing, General Lists and List ADT, List manipulations, Single, double and circular lists. Stacks and Stack ADT,
Stack Manipulation, Prefix, infix and postfix expressions, recursion. Queues and Queue ADT, Queue manipulation.

UNIT – II
Sparse Matrix Representation (Array and Link List representation) and arithmetic (addition, subtraction and multiplication), polynomials and
polynomial arithmetic.
Trees, Properties of Trees, Binary trees, Binary Tree traversal, Tree manipulation algorithms, Expression trees and their usage, binary search trees,
AVL Trees, Heaps and their implementation, Priority Queues, B-Trees, B* Tree, B+ Tree

UNIT – III
Sorting concept, order, stability, Selection sorts (straight, heap), insertion sort (Straight Insertion, Shell sort), Exchange Sort (Bubble, quicksort),
Merge sort (External Sorting) (Natural merge, balanced merge and polyphase merge). Searching – List search, sequential search, binary search,
hashing methods, collision resolution in hashing.

UNIT – IV
Disjoint sets representation, union find algorithm, Graphs, Graph representation, Graph Traversals and their implementations (BFS and DFS).
Minimum Spanning Tree algorithms, Shortest Path Algorithms

Textbook(s):
1. Richard Gilberg , Behrouz A. Forouzan, “Data Structures: A Pseudocode Approach with C, 2nd Edition, Cengage Learning, Oct 2004
2. E. Horowitz, S. Sahni, S. Anderson-Freed, "Fundamentals of Data Structures in C", 2nd Edition, Silicon Press (US), 2007.

References:
1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, 2nd Edition, Pearson, September, 1996
2. Robert Kruse, “Data Structures and Program Design in C”, 2nd Edition, Pearson, November, 1990
3. Seymour Lipschutz, “Data Structures with C (Schaum's Outline Series)”, McGrawhill, 2017
4. A. M. Tenenbaum, “Data structures using C”. Pearson Education, India, 1st Edition 2003.
5. Weiss M.A., “Data structures and algorithm analysis in C++”, Pearson Education, 2014.
Data Structure
• Data Structure is a way of collecting and organizing data in such a
way that we can perform operations on these data in an effective
way
• In simple language, Data Structures are structures programmed to
store ordered data, so that various operations can be performed on
it easily

10/9/2023 4
STACKS
• STACK Data Structure stores data in an ordered manner
❑Pile of plates
❑Stack of coins

• Restrictive Data structure: LIFO (Last-In-First-Out)


❑Elements are added and removed only from one end

• WHERE IT IS REQUIRED IN COMPUTER SCIENCE?


❑FUNCTION CALLS

10/9/2023 5
Function calls: STACKS
• Consider a Function A in execution
• Function A calls another Function B
• Function B in turn calls Function C
• and Function C in turn calls Function D…
• Whenever a function calls another function,
❑the calling function is pushed onto the top of the stack
❑because after the called function gets executed
❑the control is passed back to the calling function

10/9/2023 6
Function calls: STACKS
When A calls B, A is pushed
on top of the stack. When
the execution of B is When B calls C, B is pushed
complete, the system on top of the stack. When
control will remove A from the execution of C is
the stack and continue with complete, the system
Function A its execution control will remove B from
Function B
the stack and continue
Function A with its execution
When C
calls D,
C is When D
Function C pushed has
on top executed,
Function B
of the C will be
Function C
Function A stack. removed
Function B Function B
for
Function A execution Function A Function A
10/9/2023 7
STACKS
• ARRAY IMPLEMENTATION
• LINKED LIST IMPLEMENTATION

10/9/2023 8
STACKS: ARRAY
REPRESENTATION

• Every stack has variables TOP, MAX


• TOP
❑used to store the address of the topmost element of the stack
❑position where the element will be added or deleted

• MAX
❑used to store the maximum number of elements stack can hold

• If TOP = NULL - STACK is empty


• If TOP = MAX – 1 - STACK is full (Array Index starts at 0)

10/9/2023 9
Stack Operations

• PUSH:
❑adds an element to the top of the stack

• POP:
❑removes the element from the top of the stack

• PEEP:
❑returns the value of the topmost element of stack

10/9/2023 10
STACK(Array): PUSH

1 2 3

0 1 TOP= 2 3 4

 Step 1: IF TOP = MAX – 1, then


 PRINT “OVERFLOW”
 [END OF IF]
 Step 2: SET TOP = TOP +1
 Step 3: SET STACK[TOP] = VALUE
 Step 4: END
1 2 3 4

10/9/20230 1 2 TOP= 3 4 11
STACK(Array): POP

1 2 3 4

0 1 2 TOP = 3 4 5

 Step 1: IF TOP = NULL, then


 PRINT “UNDERFLOW”
 [END OF IF]
 Step 2: SET VAL = STACK[TOP]
 Step 3: SET TOP = TOP - 1
 Step 4: END
1 2 3

10/9/2023 0 1 TOP = 2 3 4 5 12
STACK(Array): PEEP

1 2 3 4

0 1 2 TOP = 3 4 5

 Step 1: IF TOP = NULL, then


 PRINT “STACK IS EMPTY”
 [END OF IF]
 Step 2: RETURN STACK[TOP]
 Step 3: END

10/9/2023 13
STACKS: LINKED LIST
• Stacks using array required fixed size
• LINKED LIST: Two parts
❑Stores data
❑Stores the address of the next Node

• START pointer of the linked list is used as TOP

10/9/2023 14
STACK(LINKED): PUSH
• Step 1: IF AVAIL = NULL, then
• Write OVERFLOW
• Go to step 6
• [END OF IF]

• Step 2: SET New_Node = AVAIL


• Step 3: SET AVAIL = AVAIL -> NEXT
• Step 4: SET New_Node -> DATA = VAL
7 3 4 2 X
• Step 5: IF TOP= NULL, then
TOP
• SET New_Node -> NEXT = NULL
• SET TOP = New_Node
• ELSE 1 7 3 4 2 X
• SET New_Node -> NEXT = TOP TOP
• SET TOP = New_Node
• [END OF IF]
• Step 6: END
• ALLOCATE memory for the new node and name it as New_Node

10/9/2023 15
STACK(LINKED): POP

• Step 1: IF TOP = NULL, then


• Write UNDERFLOW
• Go to step 5
• [END OF IF]
1 7 3 4 2 X
• Step 2: SET PTR = TOP TOP

• Step 3: SET TOP = TOP -> NEXT


• Step 4: FREE PTR 7 3 4 2 X

• Step 5: END TOP

10/9/2023 16
STACK: APPLICATIONS
•Four Broad categories
❑Reversing Data
❑Parsing Data
❑Postponing Data usage
❑Backtracking steps

10/9/2023 17
Stacks: Reversing a list
• After creating a stack
• Read a series of numbers and PUSH them on to stack
• After end of file
• POPs the stack and
• Print the numbers in reverse order

1 7 3 4 X 1 7 3 4
TOP

10/9/2023 18
Stacks: Reversing Data
• Reverse a List
❑Convert a Decimal Number to its Binary equivalent

10/9/2023 19
Decimal to its Binary equivalent

❑Convert Decimal 233 into Binary

10/9/2023 20
Stacks: Parsing Data

• Match the parentheses in a source program

•7 – ( (X*( (X+4) /( Y+3) )+4) /(4–2))

10/9/2023 21
Parsing
• Unmatched parenthesis in an algebraic expression
❑Opening parentheses PUSH it on the stack
❑Closing parentheses POP matching opening parentheses

7 – ( ( X * ( ( X + 4 ) / (Y + 3 ) ) + 4 ) / ( 4 – 2 ) )
00122234444334444322211222210

7 - ( ( X * ( ( X + 4 ) / ( Y + 3 ) ) + 4 ) / ( 4 - 2 ) )

0 0 1 2 2 2 3 4 4 4 4 3 3 4 4 4 4 3 2 2 2 1 1 2 2 2 2 1 0

10/9/2023 22
Stacks: Postponing Data usage
• Evaluate a postfix expression
• Convert infix to postfix notation

10/9/2023 23
Infix & Postfix

• Infix Notation
❑Need parentheses to control the evaluation of the
operators (Priority)
• Postfix and prefix Notation
❑Need no Parentheses

10/9/2023 24
Infix to Postfix: Manual
Transformation
• Step 1: Fully parenthesize the expression using any explicit
parentheses and the arithmetic precedence
• Step 2: Change all infix notation in each parentheses to postfix
notation, starting from the innermost expression. (moving the
operator to the closing parenthesis)
• Step 3: Remove all parentheses.

10/9/2023 25
Infix to Postfix: Example
(A + B) * C + D + E * F – G
Step 1: Add Parentheses
(((((A + B) * C) + D) + (E * F)) – G)
Step 2: Move the operators
(((((A B +) C *) D +) (E F * ) + ) G –)
Step 3: Remove the parentheses
AB+C*D+EF* + G–

10/9/2023 26
Infix to Postfix: Algorithmic
Transformation
• Use precedence Rule
• Precedence:
• PUSH an operator into the stack, If its priority is higher than the
operator at the top of the stack
• Maintain lowest precedence for the first element in the stack and
thereafter PUSH in the stack only
• if next symbol having higher precedence
• Else POP

+ - / * ↑

10/9/2023 27
Operator precedence
• Same precedence are scanned the order is assumed to be LEFT to
RIGHT:
• A + B – C → (A + B) - C
• In Exponential RIGHT to LEFT:
•A↑B↑ C → A ↑ (B ↑ C)

10/9/2023 28
INFIX STACK POSTFIX

A+B*C-D/E
+B*C-D/E A
B*C-D/E + A
*C-D/E + AB
*
C-D/E AB
+
*
-D/E ABC
+
D/E - ABC*+
/E - ABC*+D
/
E ABC*+D
-
/
ABC*+DE
-
10/9/2023 29
ABC*+DE/-
EXAMPLE
• INFIX STRING: A +B *C↑D↑E
• POSTFIX STRING: A BCDE↑↑*+

10/9/2023 30
Operator precedence
prcd(op1, op2) = TRUE if op1 > op2
(Stack top operator has higher precedence for similar operators except ↑ )

prcd(*, +) = TRUE prcd(op, ( ) = FALSE for all op except ‘)’


prcd(+, +) = TRUE prcd( (, op ) = FALSE for all op
prcd(+, *) = FALSE prcd(op, ) ) = TRUE for all op except ‘(’
prcd(↑, ↑) = FALSE prcd( (, ) ) = FALSE DISCARD BOTH
prcd( ), op) = UNDEFINED
10/9/2023 31
Algorithm: INFIX to POSTFIX
• Opstk = the empty stack
• While (not end of input)
• {1
• Symb = next input character
• If (symb is an operand)
• Add symb to POSTFIX string
• Else {2
• while (! Empty(opstk) &&
• prcd(stacktop(opstk), symb))
• {3
• topsymb = POP(opstk)
• add topsymb to the POSTFIX string
• } 3 // end while
10/9/2023 32
Algorithm contd …
• if (empty(opstk) || symb != ‘)’)
• PUSH(opstk, symb)
• else // pop the open parenthesis and discard
• topsymb = POP(opstk)
• }2 // end else
• }1 // end while

• // output any remaining operators

• While (! Empty (opstk))


• {4
• topsymp = POP (opstk)
• add topsymb to the POSTFIX string

10/9/2023 } 4 // end while 33
• Opstk = the empty stack • if (empty(opstk) || symb != ‘)’)
• While (not end of input) • PUSH(opstk, symb)
• {1 • else // pop the open parenthesis and
discard
• Symb = next input character
• If (symb is an operand)
• topsymb = POP(opstk)
• Add symb to POSTFIX string • }2 // end else
• Else {2 • }1 // end while
• while (! Empty(opstk) &&
• prcd(stacktop(opstk), • // output any remaining operators
symb))
• {3
• While (! Empty (opstk))
• topsymb = POP(opstk) • {4
• add topsymb to the POSTFIX • topsymp = POP (opstk)
string
• add topsymb to the POSTFIX string
• } 3 // end while
• } 4 // end while

10/9/2023 34
• Opstk = the empty stack
• While (not end of input)
A+B*C-D/E
• {1 Symb = next input character
Symb=A
• If (symb is an operand)
• Add symb to POSTFIX string
• Else {2
• while (! Empty(opstk) && prcd(stacktop(opstk), symb))
• {3 topsymb = POP(opstk)
• add topsymb to the POSTFIX string
POSTFIX= A
• } 3 // end while
• if (empty(opstk) || symb != ‘)’)
• PUSH(opstk, symb)
• else // pop the open parenthesis and discard
• topsymb = POP(opstk)
• }2 // end else
• }1 // end while

• // output any remaining operators


• While (! Empty (opstk))
• {4 topsymp = POP (opstk)
• add topsymb to the POSTFIX string
10/9/2023 35
• } 4 // end while
Example: INFIX to POSTFIX
• Infix: ((A – (B+C)) * D) ↑ (E + F )
prcd(op1, op2) = TRUE
• Step 1: if op1 > op2
❑Stack: (
•prcd(*, +) = TRUE
❑Postfix: •prcd(op, ( ) = FALSE
except ‘)’
•prcd(+, +) = TRUE
• Step 2: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, op ) = FALSE
❑Stack: ( ( •prcd(+, *) = FALSE
•prcd(op, ) ) = TRUE
❑Postfix: except ‘(’
•prcd(↑, ↑) = FALSE
• Step 3: ((A – (B+C)) * D) ↑ (E + F ) •prcd( (, ) ) = FALSE
DISCARD BOTH
❑Stack: ( ( •prcd( ), op) = UNDEFINED

❑Postfix: A
10/9/2023 36
Example contd..
prcd(op1, op2) = TRUE
• Step 4: ((A – ( B+C)) * D) ↑ (E + F )
if op1 > op2
❑Stack: ( ( –
•prcd(*, +) = TRUE
❑Postfix: A •prcd(op, ( ) = FALSE
except ‘)’
• Step 5: ((A – (B+C)) * D) ↑ (E + F ) •prcd(+, +) = TRUE
•prcd( (, op ) = FALSE
❑Stack: ( ( – (
•prcd(+, *) = FALSE
❑Postfix: A •prcd(op, ) ) = TRUE
except ‘(’
•prcd(↑, ↑) = FALSE
• Step 6: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, ) ) = FALSE
❑Stack: ( ( – ( DISCARD BOTH
•prcd( ), op) = UNDEFINED
❑Postfix: A B

10/9/2023 37
Example contd..
prcd(op1, op2) = TRUE
• Step 7: ((A – ( B+C)) * D) ↑ (E + F ) if op1 > op2
❑Stack: ( ( – ( +
•prcd(*, +) = TRUE
•prcd(op, ( ) = FALSE
❑Postfix: A B
except ‘)’
•prcd(+, +) = TRUE
• Step 8: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, op ) = FALSE
( ( – ( + •prcd(+, *) = FALSE
❑Stack:
•prcd(op, ) ) = TRUE
❑Postfix: A B C except ‘(’
•prcd(↑, ↑) = FALSE
• Step 9: ((A – (B+C)) * D) ↑ (E + F ) •prcd( (, ) ) = FALSE
❑Stack: ( ( – ( + DISCARD BOTH
•prcd( ), op) = UNDEFINED
❑Postfix: A B C +

10/9/2023 38
Example contd..
prcd(op1, op2) = TRUE
• Step 6B: ((A – ( B+C)) * D) ↑ (E + F ) if op1 > op2
❑Stack: ( ( – (
•prcd(*, +) = TRUE
•prcd(op, ( ) = FALSE
❑Postfix: A B C +
except ‘)’
•prcd(+, +) = TRUE
• Step 7: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, op ) = FALSE
❑Stack: ( ( – •prcd(+, *) = FALSE
•prcd(op, ) ) = TRUE
❑Postfix: A B C + - except ‘(’
•prcd(↑, ↑) = FALSE
• Step 7B: ((A – (B+C)) * D) ↑ (E + F ) •prcd( (, ) ) = FALSE
❑Stack: ( ( DISCARD BOTH
•prcd( ), op) = UNDEFINED
❑Postfix: A B C + -

10/9/2023 39
Example contd..
prcd(op1, op2) = TRUE
• Step 8: ((A – ( B+C)) * D) ↑ (E + F ) if op1 > op2
❑Stack: ( *
•prcd(*, +) = TRUE
•prcd(op, ( ) = FALSE
❑Postfix: A B C + -
except ‘)’
•prcd(+, +) = TRUE
• Step 9: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, op ) = FALSE
❑Stack: ( * •prcd(+, *) = FALSE
•prcd(op, ) ) = TRUE
❑Postfix: A B C + - D except ‘(’
•prcd(↑, ↑) = FALSE
• Step 10: ((A – (B+C)) * D) ↑ (E + F ) •prcd( (, ) ) = FALSE
❑Stack: ( * DISCARD BOTH
•prcd( ), op) = UNDEFINED
❑Postfix: A B C + - D *

10/9/2023 40
Example contd..
prcd(op1, op2) = TRUE
• Step 11: ((A – ( B+C)) * D) ↑ (E + F ) if op1 > op2
❑Stack: (
•prcd(*, +) = TRUE
•prcd(op, ( ) = FALSE
❑Postfix: A B C + - D*
except ‘)’
•prcd(+, +) = TRUE
• Step 12: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, op ) = FALSE
❑Stack: ↑ •prcd(+, *) = FALSE
•prcd(op, ) ) = TRUE
❑Postfix: A B C + - D * except ‘(’
•prcd(↑, ↑) = FALSE
• Step 13: ((A – (B+C)) * D) ↑ (E + F ) •prcd( (, ) ) = FALSE
❑Stack: DISCARD BOTH
↑ ( •prcd( ), op) = UNDEFINED
❑Postfix: A B C + - D *

10/9/2023 41
Example contd..
prcd(op1, op2) = TRUE
• Step 14: ((A – ( B+C)) * D) ↑ (E + F ) if op1 > op2
❑Stack: ↑ ( •prcd(*, +) = TRUE
•prcd(op, ( ) = FALSE
❑Postfix: A B C + - D*E
except ‘)’
•prcd(+, +) = TRUE
• Step 15: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, op ) = FALSE
❑Stack: •prcd(+, *) = FALSE
↑ ( +
•prcd(op, ) ) = TRUE
❑Postfix: A B C + - D * E except ‘(’
•prcd(↑, ↑) = FALSE
• Step 16: ((A – (B+C)) * D) ↑ (E + F ) •prcd( (, ) ) = FALSE
❑Stack: ↑ ( + DISCARD BOTH
•prcd( ), op) = UNDEFINED
❑Postfix: A B C + - D *E F

10/9/2023 42
Example contd..
prcd(op1, op2) = TRUE
• Step 17: ((A – ( B+C)) * D) ↑ (E + F ) if op1 > op2
❑Stack: ↑ ( +
•prcd(*, +) = TRUE
❑Postfix: A B C + - D*E+ •prcd(op, ( ) = FALSE
except ‘)’
• Step 17B: ((A – (B+C)) * D) ↑ (E + F ) •prcd(+, +) = TRUE
•prcd( (, op ) = FALSE
❑Stack: ↑ ( •prcd(+, *) = FALSE
❑Postfix: A B C + - D * E +
•prcd(op, ) ) = TRUE
except ‘(’
•prcd(↑, ↑) = FALSE
• Step 18: ((A – (B+C)) * D) ↑ (E + F )
•prcd( (, ) ) = FALSE
❑Stack: DISCARD BOTH
•prcd( ), op) = UNDEFINED
❑Postfix: A B C + - D *E F + ↑

10/9/2023 43
INFIX to PREFIX

• STEP 1: Reverse the INPUT string


• STEP 2: Apply POSTFIX operations to make string in postfix
• STEP 3: Reverse to make prefix notation

10/9/2023 44
Example: INFIX to PREFIX
• Infix: ((A – (B+C)) * D) ↑ (E + F )
• Step 1: Reverse the input string
(F + E ) ↑ (D * ( ( C + B ) – A ) )
• Step 2: Apply Postfix
FE+ DCB+A-*↑
• Step 3: Reverse the postfix string
• ↑ * -A + BC D + E F

10/9/2023 45
Evaluating a postfix expression
• Each operator in a postfix string refers to the previous two
operands in the string
• Each time read an operand ➔ push into the stack
• When we reach an operator its operand will be the top two
elements on the stack
• POP these two elements, perform operation on them
• PUSH the result on the stack

10/9/2023 46
6 2 3+-382/+*2↑3+
Symb Opnd1 Opnd2 Value opndstk
6 6
2 62
3 623
+ 2 3 5 65
- 6 5 1 1
3 13
8 138
2 1382
/ 8 2 4 134
+ 3 4 7 17
* 1 7 7 7
2 72
↑ 7 2 49 49
3 10/9/2023
49 3 47

+ 49 3 52 52
Size of the operand stack?
• Maximum size of the operand stack
❑Number of operands (theoretically less than the size)

10/9/2023 48
ALGORITHM: Postfix expressions
• Step 1: opndstk = the empty stack
• // scan the input string reading one element at a time into symb
• Step 2: while (not end of input)
• { symb = next input character
• if (symb == operand)
• PUSH (opndstk, symb)
• else { // operator
• opnd2 = POP(opndstk)
• opnd1 = POP (opndstk)
• value = result of applying symb to opnd1 & opnd2
• PUSH (opndstk, value)
• }
• } [END OF WHILE]
• return (POP(opndstk))
10/9/2023 49
Stacks: Backtracking steps
• Choose between two or more paths

START

GOAL

10/9/2023 50
More Application of STACKS
• QUICK SORT(Divide & Conquer)
• Tower of Hanoi

10/9/2023 51
Tower of Hanoi

• Suppose three pegs labeled A, B & C


• One Disk need to move from A to C

10/9/2023 52
Tower of Hanoi
• Suppose three pegs labeled A, B & C
• First step the Disk need to move from A to B
• Second step Disk from A to C
• And now in last step from B to C

10/9/2023 53
Tower of Hanoi

10/9/2023 54
Tower of Hanoi
1 ( A, C, B) A→B

2 (A, B, C) A→C A→C

1 (B, A, C) B→C

3 (A, C, B) A→B A→B A→B

1 ( C, B, A) C →A

2 (C, A, B) C→B C→B

1 (A, C, B) A→B

4 (A, B, C) A→C A→C

1 ( B, A, C) B→C

2 (B, C, A) B→A B→A

1 (C, B, A) C →A

3 (B, A, C) B→C B→C B→C

1 ( A, C, B) A→B

2 (A, B, C) A→C A→C


10/9/2023 55
1 (B, A, C) B→C
Tower of Hanoi
• General Notation: A=FROM, B=VIA, C=TO
• IF N = 1
❑Tower (1, FROM, VIA, TO)

• IF N > 1
❑Tower (N – 1, FROM, TO, VIA)
❑Tower (1, FROM, VIA, TO)
❑Tower (N – 1, VIA, FROM, TO)

10/9/2023 56
• General Notation: A=FROM, B=VIA, C=TO
• IF N = 1
❑Tower (1, FROM, VIA, TO)

• IF N > 1
❑Tower (N – 1, FROM, TO, VIA)
❑Tower (1, FROM, VIA, TO)
❑Tower (N – 1, VIA, FROM, TO)

❑4 Disks to be moved from A to C (N>1)


❑Tower (3, A, C, B)
❑Tower (2, A, B, C)
❑ Tower ( 1, A, C, B)
❑ Tower (1, A, B, C)
❑ Tower ( 1, B, A, C)

❑Tower (1, A, C, B)
❑Tower (2, C, A , B)
❑ Tower (1, C, B, A)
❑ Tower (1, C, A, B)
❑ Tower (1, A, C, B)

❑Tower (1, A, B, C)
❑Tower (3, B, A, C)
10/9/2023 57
QUEUES
• Stores data in an ordered manner
• Element inserted first is the first one to be taken out
• FIFO (first in first out)
• Elements in a queue are added at one end REAR
• Element are removed from the other end FRONT

10/9/2023 58
QUEUES
• ARRAY IMPLEMENTATION
• LINKED LIST IMPLEMENTATION

10/9/2023 59
QUEUES: ARRAY
REPRESENTATION

• Every Queue has variables FRONT, REAR


• FRONT
❑position where the element will be deleted

• REAR
❑position where the element will be added

• If FRONT = – 1 & REAR = – 1 - underflow


• If REAR = MAX – 1 - overflow (Array Index starts at 0)

10/9/2023 60
QUEUE(Array): Insert/enqueue
1 2 3

FRONT=0 1 REAR= 2 3 4

 Step 1: IF REAR= MAX – 1, then


 PRINT “OVERFLOW”
 [END OF IF]
 Step 2: IF FRONT == - 1 AND REAR = - 1, then
 SET FRONT = REAR = 0
 ELSE
 SET REAR = REAR + 1
 [END OF IF]
 Step 3: SET QUEUE[REAR] = NUM
 Step 4: END
1 2 3 4

FRONT=0
10/9/2023 1 2 REAR= 3 4 61
QUEUE(Array): Delete/dequeue
1 2 3 4

FRONT=0 1 2 REAR = 3 4 5

 Step 1: IF FRONT = - 1 OR FRONT > REAR, then


 PRINT “UNDERFLOW”
 ELSE
 SET VAL = QUEUE[FRONT]
 SET FRONT = FRONT + 1
 [END OF IF]
 Step 4: END
2 3 4

10/9/2023 0 FRONT=1 2 REAR=3 4 5 62


QUEUE(Array): Drawback of QUEUES
1 2 3 4 5

FRONT=0 1 2 3 REAR=4

 Insertion not possible as REAR=Max -1


3 4 5

0 1 FRONT=2 3 REAR=4

 Two successive Deletion


 Even now Insertion is not possible as REAR=Max -1
 This is Major Drawback of QUEUES
 Solution may be by shifting but its time consuming
 Alternative is CIRCULAR QUEUES

10/9/2023 63
CIRCULAR QUEUE
• First index comes right after the last index
• Circular queue will be full when
FRONT=0 & REAR= MAX – 1
Q[0]

Q[4] Q[1]

Q[3] Q[2]

10/9/2023 64
CIRCULAR QUEUE
• First index comes right after the last index
• Circular queue will be full when
FRONT=0 & REAR= MAX – 1
Q[0]
• Position: i
Q[4] Q[1]
• Next position: (i + 1) Modulo N
• Previous position: (i + N - 1) Modulo N
Q[3] Q[2]

10/9/2023 65
CIRCULAR QUEUE(Array): Insert
1 2 3 4 5
 EnQueue = Insert F=0 1 2 3 R=4

 Step 1: IF FRONT = 0 AND REAR = MAX - 1, then


 PRINT “OVERFLOW”
0 1 2 3 4
 ELSE IF FRONT = - 1 AND REAR = - 1, then F=R=-
1
 SET FRONT = REAR = 0
3 4 5
 ELSE IF REAR = MAX – 1 AND FRONT != 0
0 1 F=2 3 R=4
 SET REAR = 0
 ELSE
 SET REAR = REAR + 1 1 2 3
F=0 1 R=2 3 4
 [END OF IF]
 Step 2: SET QUEUE[REAR] = VAL
 10/9/2023
Step 3: END 66
CIRCULAR QUEUE(Array): Delete

 Dequeue
 Step 1: IF FRONT = - 1, then 0 1 2 3 4
 PRINT “UNDERFLOW” F=R=-1

 [END OF IF]
5
 Step 2: SET VAL = QUEUE[Front] F=R=4
0 1 2 3
 Step 3: IF FRONT = REAR, then
 SET FRONT = REAR = -1
4 5
 ELSE IF FRONT = MAX - 1
R=0 1 2 3 F=4
 SET FRONT = 0
 ELSE
 SET FRONT = FRONT + 1
 [END OF IF]
 Step 4: END
10/9/2023 67
QUEUES: LINKED LIST
• Queues using array required fixed size
• LINKED LIST: Two parts
❑Stores data
❑Stores the address of the next Node
• START pointer of the linked list is used as FRONT

10/9/2023 68
QUEUE(LINKED): Insert
• EnQueue
• Step 1: IF AVAIL = NULL, then
• Write OVERFLOW
• Go to step 6
• [END OF IF]

• Step 2: SET New_Node = AVAIL


• Step 3: SET AVAIL = AVAIL -> NEXT F=R=-1
• Step 4: SET New_Node -> DATA = VAL
• Step 5: IF FRONT= NULL, then 7 3 4 2 X
• SET FRONT = REAR = New_Node F R
• SET FRONT -> NEXT= REAR -> NEXT = NULL
• ELSE
• SET REAR -> NEXT = New_Node
• SET REAR = New_Node
7 3 4 2 1 X
• SET REAR -> NEXT = NULL
F R
• [END OF IF]
• Step 6: END
10/9/2023 69
• ALLOCATE memory for the new node and name it as New_Node
QUEUE(LINKED): Delete

Dequeue
• Step 1: IF FRONT= NULL, then
• Write UNDERFLOW
1 7 3 4 2 X
• Go to step 5
• [END OF IF] F R

• Step 2: SET PTR = FRONT


• Step 3: SET FRONT= FRONT-> NEXT
• Step 4: FREE PTR 7 3 4 2 X

• Step 5: END F R

10/9/2023 70
DEQueue
• DEqueue → DOUBLE-ENDED QUEUE (circular)
• Element can be inserted or deleted at either end
• HEAD-TAIL linked list
• Two pointers are maintained RIGHT & LEFT
• Two variants
• Input restricted:
❑Insertion at one end but Deletion both ends

• Output restricted:
❑Deletion at one end but Insertion both ends

2 3 4

0 LEFT=1 2 RIGHT=3 4 5
10/9/2023 71
Priority Queues
• Collection of elements and each has been assigned a priority
• Order in which the elements are processed (deleted)
❑The element of higher priority is processed before any element of lower
priority
❑Two elements with the same priority are processed according to the
order in which they were added in the queue

10/9/2023 72
Priority Queue: Array
Representation
• Separate queue for each level of priority

Priority FRONT REAR TASKS

1 2 2 1 2 3 4 5 6

2 1 3 1 A

PRIORITY
3 5 1 2 B C D

4 0 0 3 M G H

5 3 3 4

5 F

10/9/2023 73
Priority Queue: Linked Representation
• One way List representing a Priority Queue

A1 B 2 C 2 D3 X
HEAD

START INFO PRN LINK

5 1 B 2 3

AVAIL 3 C 2 4

2 4 D 3 0
10/9/2023 74
5 A 1 1

You might also like