Вы находитесь на странице: 1из 194

Data Structures Through C

Student Handout Book


Contents
Lecture 1: C Revision I
Importance of data structures
Data types in C
Instructions and its types
The decision control instruction
Working of logical operators
Different types of loops
Difference between break, continue and exit
Case control instruction
Lecture 2: C Revision II
Pointers and their usage
Function call – by value and by reference
Arrays and their working
Lecture 3: Searching
Operations performed on an array
What are algorithms
Important features of an algorithm
Conventions to be followed while writing an algorithm
Linear search and Binary search
Lecture 4: Searching and Frequency count
Analyzing an algorithm
Rate of increase for growth rate with respect to Big Oh notation
Lecture 5: Analysis of Searching Method
Tools to calculate time complexity
Cases to be considered while analyzing an algorithm
Analysis of Linear search and Binary search
Lecture 6: Hashing
Hashing techniques:
o Division method
o Mid-Square method
o Folding method
o Digit analysis method
Linear and Quadratic probing

i
Lecture 7: Sorting
Selection sort and its analysis
Bubble sort and its analysis
Radix sort
Lecture 8: Sorting and Recursion
Insertion sort
Recursive functions
Lecture 9: Quick Sort
Splitting mechanism
Quick sort algorithm
Quick sort program
Lecture 10: Structures
Defining and using structures
Array of structures
Copying structure variables
Nested structures
Passing structure elements
Passing structures
Lecture 11: Structures and Polynomials
Polynomial representation
Passing array of structures
General operations on polynomials
Lecture 12: Two Dimensional Arrays
Using two dimensional arrays
Saddle point of an array
Lecture 13: Sparse Matrices
Sparse matrices
Passing arrays
3 tuple conversion
Lecture 14: Transpose of Sparse Matrices
Transpose of a sparse matrix
Lecture 15: Addition of Sparse Matrices
Addition of sparse matrices
Lecture 16: Multiplication of Sparse Matrices
Matrix multiplication
ii
Multiplication of sparse matrices
Lecture 17: Storage
Storage - two dimensional arrays
3 dimensional arrays
4 dimensional arrays
n - dimensional arrays
Lecture 18: Dynamic memory allocation
Limitations of arrays
Dynamic memory allocation
Steps involved in memory allocation
Lecture 19: Linked Lists
Memory leaks
Linked lists
Creation of linked lists
Lecture 20: Operations on Linked Lists I
Appending a new node to a link list
Adding a new node at the beginning of a linked list
Adding a new node at a specified position in a linked list
Deleting a node from a linked list
Deleting all the nodes in a list
Lecture 21: Operations on Linked Lists II
Arranging the elements in a linked list in ascending order
Sorting the elements in a linked list
Lecture 22: Operations on Linked Lists - III
Reversing a linked list
Merging two linked lists
Lecture 23: Operations on Linked Lists - IV
Concatenating two linked lists
Addition of polynomials using linked lists
Lecture 24: Circular Linked Lists
Circular linked lists
Adding a new node to a circular list
Deleting an existing node from a circular list
Counting the nodes of a circular linked list
Displaying the nodes in a circular linked list
iii
Lecture 25: Doubly Linked Lists
Doubly linked lists
Common operations on a doubly linked list
Lecture 26: Sparse Matrices as Linked Lists I
Representing sparse matrices in the form of linked lists
Lecture 27: Sparse Matrices as Linked Lists II
Add new node to linked Lists
Display contents of Linked List
Delete all nodes in the Linked List
Program to implement sparse matrices as linked lists
Lecture 28: Recursive LL
Recursive count( )
Recursive compare( )
Recursive copy( )
Recursive append( )
Lecture 29: Linked Lists Using Unions
What are unions
Declaring unions
Using unions
Generalized linked lists
Lecture 30: Generalized Linked Lists
Copying generalized linked lists
Depth of generalized linked lists
Comparing generalized linked lists
Lecture 31: Stacks
Stack and its utilities
Program to implement stack as an array
Lecture 32: Stack as a Linked List
Program to implement stack as a linked list
Lecture 33: Stack Expressions
Different form of expressions
Lecture 34: Stack Operations
Infix to Postfix conversion
Lecture 35: Postfix
Evaluation of Postfix form
iv
Lecture 36: Infix To Prefix
Infix to Prefix conversion
Lecture 37: Postfix To Prefix
Evaluation of Prefix form
Postfix to Prefix conversion
Lecture 38: Postfix To Infix
Postfix to Infix conversion
Lecture 39: More Conversions
Prefix to Postfix conversion
Prefix to Infix conversion
Lecture 40: Queue I
Queue
Program to implement queue as an array
Lecture 41: Queue II
Limitations of queue
Circular queue
Lecture 42: Deque and Priority Queue
Deque
Program to implement deque
Priority queue
Lecture 43: Trees
What are trees
Tree terminology
Strictly and complete trees
Lecture 44: Tree Traversal
Preorder, Postorder and Inorder traversal
Reconstruction of trees
Lecture 45: Binary Search Trees I
Representing trees using arrays
Linked representation of trees
Binary search trees
Lecture 46: Binary Search Trees II
Traversing of trees using Inorder, Preorder and Postorder
Non recursive Inorder traversal of trees
Non recursive Preorder traversal of trees
v
Non recursive Postorder traversal of trees
Comparison of two trees
Lecture 47: Binary Tree
Successor and predecessor
Insertion of a node in a binary search tree
Deleting an existing node from a binary search tree
Searching a node in a binary search tree
Lecture 48: Threaded Binary Tree
Threaded binary trees
Representation of threaded binary trees
Inserting a node in a threaded binary tree
Traversing the threaded binary tree in inorder
Lecture 49: Heap
Heap
Creation of a heap
Heap sort
Lecture 50: AVL Trees and B Tree
Program to create a heap
AVL tree
2 - 3 tree
B tree
Lecture 51: Graphs
Graphs
Terminology associated with graphs
Representation of graphs
Adjacency list
Lecture 52: Adjacency Multilist
Adjacency matrices
Adjacency multilist
Orthogonal representation of graphs
Lecture 53: Depth First Search
Depth first search
Program to implement depth first search algorithm
Lecture 54: Breadth First Search
Breadth first search
vi
Program to implement breadth first search algorithm
Lecture 55: Spanning Tree
What is a spanning tree
Cost of spanning tree
Kruskal’s algorithm to determine minimum cost spanning tree
Lecture 56: Dijkstra’s Algorithm
Dijkstra’s algorithm to determine minimum cost spanning tree
AOV network
Lecture 57: Memory Management I
Memory management
First fit algorithm
Best fit algorithm
Lecture 58: Memory Management II
Next fit algorithm
Lecture 59: Garbage Collection
Garbage Collection
Marking algorithm
Compaction
Lecture 60: File Organization
Files
File Organization

vii
C Revision - I
Yashavant Kanetkar

Objectives
The importance of data structures
The data types in C
What are instructions and its types
The decision control instruction
Working of logical operators
Different types of loops
Difference between break, continue and exit
Case control instruction

Data Structures
What are they
Way of organizing data and opns. performed on it
Where are they used
- Car Parking
- File Storage
- Dictionary
- Shortest route
- Searching Law Books Ô¿²¹«¿¹»
- Sorting
- Device Drivers
- Evaluation of expression
- Networking

Data Structures Through C / Lecture 01 1


C Data Types
int char float

Size: 2 Bytes Size: 1Byte Size: 4 Bytes


Specifier: %i %d Specifier: %c Specifier: %f

C Instructions
Type Declaration Instructions
int i, j ; char ch, dh ; float a, b ;
Arithmetic Instructions
c = 5 / 9.0 * ( f - 32 ) ;
+ - * / % - Arithmetic operators
Input / Output Instructions
printf( ), scanf( )
Control Instructions
Control the sequence of execution of instructions
Types - Sequence - Default
- Decision
- Repetition
- Case

Decision Control Instruction


Implementation - if-else, ? :
General Form
if ( condition )
Relational Operators
statement1 ;
else Logical Operators
statement2 ;
Cond. is usually built using <, >, <=, >=, = =, !=
&& || !
else block is optional
Condition – True – Replaced by 1
Condition – False – Replaced by 0
Truth in C is nonzero
Falsity is zero

Data Structures Through C / Lecture 01 2


Working of && And ||
cond1 cond2 cond1 && cond2 cond1 || cond2

True True True True


False False False False
True False False True
False True False True

cond1 && cond2 cond1 || cond2

cond2 executed cond2 executed


only if cond1 is only if cond1 is
true false

Repetition Control Instruction


for ( i = 1; i <= 10 ; i++ ) Tips
printf ( "Hi" ) ;
for - Finite no. of times
i=1; while - Unknown no. of times
while ( i <= 10 ) do - while - At least once
{
Loop counters can be
printf ( "Hi" ) ;
i++ ; int, long int, float or char
} Loop counters can be
i=1; incremented or decremented
do by any suitable step value
{
printf ( "Hi" ) ;
i++ ;
} while ( i <= 10 ) ;

Effects of break & continue

while ( …. ) for ( .. ; .. ;… ) do
{ { {
if ( cond1 ) if ( cond1 ) if ( cond1 )
break ; break ; break ;
if ( cond2 ) if ( cond2 ) if ( cond2 )
continue ; continue ; continue ;
} } } while ( …. ) ;

break - Terminates Loop


exit( ) - Terminates Program

Data Structures Through C / Lecture 01 3


Case Control Instruction
n+3/a +2
main( ) 4+3/5 +2
{
switch ( expression )
{
case constant expression :

case constant expression : 3+2%5

case constant expression :

default :

}
}

Data Structures Through C / Lecture 01 4


Searching
Yashavant Kanetkar

Objectives
Operations performed on an array
What are algorithms
Important features of algorithms
Conventions to follow while writing an algorithm
Linear search and Binary search

Algorithm
Method of accomplishing a task in a finite number of steps
Origin - Persian Mathematician - Abu Jaffer Al-Khowarizmi
Aka - Recipe, Method, Technique, Procedure, Routine
Important Features:

Input- Must have zero or more inputs


Output - Must have one or more outputs
Finiteness - Must terminate after finite no. of steps
Definiteness- Each step must be unambiguously defined
Effectiveness - All operations must be sufficiently basic
Types:
Iterative - Repetition using loop
Recursive- Divide and Conquer

Data Structures Through C / Lecture 03 1


Array Operations
Operations Description
Traversal Processing each element in the array
Search Finding the location of an element with
a given value
Insertion Adding a new element to an array
Deletion Removing an element from an array
Sorting Organizing the elements in some order
Merging Combing two arrays into a single array

Linear Search
main( )
{
int a[ ] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i, num ;
printf ( "Enter no. to search: " ) ;
scanf ( "%d", &num ) ;
for ( i = 0 ; i <= 9 ; i++ )
{
if ( a[ i ] == num )
break ;
}
if ( i == 10 )
printf ( "No such number in array" ) ;
else
printf ( "Number is at position %d", i ) ;
}

Binary Search l m u
main( ) 1 2 3 9 11 13 17 25 57 90
{
int a[ ] = { 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 } ;
int l = 0, u = 9, m, num ;
printf ( "Enter number to search: " ) ;
scanf ( "%d", &num ) ;
57
while ( l <= u )
{
m=(l+u)/2;
if ( a[m] == num )
{
printf ( "No. is at position %d ", m ) ; exit( ) ;
}
a[m] > num ? ( u = m - 1 ) : ( l = m + 1 ) ;
}
printf ( "Element is not present in the array." ) ;
}

Data Structures Through C / Lecture 03 2


Searching &
Frequency Count
Yashavant Kanetkar

Objectives

Analyzing an algorithm
Rate of increase for growth rate with respect to
Big Oh notation

Analysis Of Algorithms
Determining

Time Requirement Space Requirement

Difficulty Cheaper - Not so relevant


Machine dependent
Language dependent
Compiler dependent
Iterative - WD in loop
Recursive - WD in break & make
Solution
Don’t calculate exact time
Calculate approx. no. of operns. for given input
No,. of opns Time

Data Structures Through C / Lecture 04 1


Example - Biggest of 4
3 comparisons
Algorithm 1 Algorithm 2
if ( a > b ) else big = a
if ( a > c ) if ( b > c ) if ( b > big )
if ( a > d ) if ( b > d ) big = b
return a return b end if
else else if ( c > big )
return d return d
big = c
end if end if
else end if
else if ( d > big )
if ( c > d )
if ( c > d ) return c big = d
return c else end if
else return d return big
return d end if
end if end if
end if end if

What To Count
Multiplication of Matrices- Number of multiplications
Searching - Number of comparisons
Sorting - Number of comparisons
Count chars in a file

for ( i = 0 ; i <= 255 ; i + + )


a[ i ] = 0 ;
while ( ( ch = getc ( fp ) ) != EOF )
a[ ch ] + + ;
N Opns. in Loop1 Opns. in Loop2 Total
500 256 + 256 + 256 500 + 500 + 500 2268
( 33%) ( 66%)
50000 256 + 256 + 256 50000 + 50000 + 50000 150768
( 1%) ( 99%)

Fibonacci Series
1 fibonacci ( ) Line no. No. of execution
2 {
3 old = 1 ;
4 new = 1 ;
5 n = 20 ;
6 for ( i = 1 ; i < n ; i + + )
7 {
8 a = old + new ;
9 printf ( "%d ", a ) ;
10 old = new ;
11 new = a ;
12 }
13 }
Ignoring the const 5 & 2
complexity -> O( n )

Data Structures Through C / Lecture 04 2


Exercise
Determine the frequency counts for all statements in the
following two program segments:
1 for ( i = 0 ; i < n ; i + + )
2 { Line no. No. of exec.
3 for ( j = 0 ; j < i ; j + + )
4 {
5 for ( k = 0 ; k < j ; k + + )
6 {
7 x++;
8 } n(1+i+2ij)
9 } O(n)
10 }
1 i=0 Line no. No. of exec.
2 while ( i < n )
3 {
4 x=x+1;
5 i= i+1;
6 } O(n)

Rate of Increase
n log n n log n n2 n3 2n
1 0.0 0.0 1.0 1.0 2.0
2 1.0 2.0 4.0 8.0 4.0
5 2.3 11.6 25.0 125.0 32.0
10 3.3 33.2 100.0 1000.0 1024.0
15 3.9 58.6 225.0 3375.0 32768.0
20 4.3 86.4 400.0 8000.0 1048576.0
30 4.9 147.2 900.0 27000.0 1073741824.0
40 5.3 212.9 1600.0 64000.0 1099511627776.0
50 5.6 282.2 2500.0 125000.0 1125899906842620.0
O( 1 ) - const., O( n ) - linear, O( n2 ) - quadratic, O( n3 ) - cubic
O( 2n ) - exponential
O( log n ) is faster than O( n )
O( n log n ) is faster than O( n2 ) but not as good as O( n )

Exercise
For which range of values would the algorithm whose order
of magnitude is n3 be better than an algorithm who order of
magnitude is 2n
Range Better
n n3 2n
1 1.0 2.0
2 8.0 4.0
5 125.0 32.0
6 216.0 64.0
7 343.0 128.0
8 512.0 256.0
9 729.0
10 1000.0 1024.0
15 3375.0 32768.0
20 8000.0 1048576.0
30 27000.0 1073741824.0
40 64000.0 1099511627776.0
50 125000.0 1125899906842620.0

Data Structures Through C / Lecture 04 3


Analysis Of
Searching Methods
Yashavant Kanetkar

Objectives
Tools to calculate time complexity
Cases to be considered while analyzing
algorithms
Analysis of Linear search and Binary search

Classification Of Growth
Rate of growth is dominated by largest term in an equation
Neglect terms that grow more slowly
Leftover is known as order of the algorithm
Algos. are grouped into 3 categories based on their order
Big Omega - (f)
If g( x ) ( f ), g( n ) >= cf( n ) for all n >= n0 (c = const.)
Represents class of funcns that grow at least as fast as f
Big Oh - O( f )
If g( x ) O( f ), g( n ) <= cf( n ) for all n >= n0 (c = const.)
Represents class of funcns that grow no faster than f
Big Theta - ( f )
( f ) = ( f ) O( f )
Represents class of funcns that grow as fast as f

Data Structures Through C / Lecture 05 1


Analysis Of Linear Search
linearsearch ( int *list, int value, int n )
{
Best Worst Avg.
for ( i = 0 ; i < n ; i + + )
{ 1 N N+2
if ( value == list [ i ] ) 2
return i ;
}
Possible inputs
return -1 ;
Probability of each input
}
The value being searched
is found in first location
The value being searched matches the last elements
in the list
The value being searched is not present in the list

Average Case
N
1 i
A( N ) = +N
Probability
N+1 * i=1
N
1 1
i
A( N ) =
N+1
i=1
+ N+1 *N
1 N(N+1) N
A( N ) = +N+1
N+1 * 2
N N
+1_
N 1
A( N ) = + N+1 =
2 2 N+1
N+2
A( N )
2
1
(As n gets very large, becomes almost 0)
N+1

Analysis Of Binary Search


bisearch ( int *a, int x ) Halving nature of algo.
{
lower = 0 ; upper = 10 ; N = 2k - 1
while ( lower <= upper )
2k - 1 - 1, 1, 2k - 1 - 1
{
mid = ( lower + upper ) / 2 ; K = 3, 23 - 1 = 7, N = 7
switch ( compare ( x, a[ mid ] ) ) 23 - 1 - 1, 1, 23 - 1 - 1
{ 3, 1, 3
case '>' : K = 2, 22 - 1 = 3, N = 3
lower = mid + 1 ; break ; 22 - 1 - 1, 1, 22 - 1 - 1
case '<' : 1, 1, 1
upper = mid - 1 ; break ; N = 2k - 1
case '=’ : log2 2k = log2 ( N + 1 )
printf ( "%d ", mid ) ; exit( ) ;
k log2 2 = log 2 ( N + 1 )
} Best Worst k = log2 ( N + 1 )
}
1 log ( N + 1 )
}

Data Structures Through C / Lecture 05 2


Hashing
Yashavant Kanetkar

Objectives

Hashing Techniques
Division method
Mid – Square method
Folding method
Digit Analysis method
Linear and quadratic probing

Hashing Functions
Division
Mid - Square
Folding
Digit Analysis

Data Structures Through C / Lecture 06 1


Division
3229329 4231176 7621913 9812427 2178115 4031231

Store elements as per hash value 0


Hash value - index based 1 4031231
Hash value = no. % 10
2
If hash value clashes - collision
- chaining (not efficient) 3 7621913
- rehashing 4
1431327 5 2178115
6 4231176
7 9812427
8 1431327
9 3229329
Linear Probing

Mid - Square
Identifiers - A = 1, ..., Z = 26, 0 = 27, 1 = 28, ..., 9 = 36
Find octal equivalent of each character
Square the octal equivalent
Use middle bits of square as hash value
Table size = 2r, r is no. of middle bits
X X1 (X1) 2
A 01 1
B 02 4
... ... ...
Y 31 1701
Z 32 2000
0 33 2101
1 34 2204
A1 134 20420
A2 135 20711
CAT 030124 125620

Folding
Distribute digits in multiple partitions
Excluding last make all partitions equal
Add partition values to get hash value

No. Of
Partition
Digits
1 1
2 2
3 1, 2 CAT 030124
4 1, 1, 2
5 2, 2, 1 0 3 0 1 24 28
6 1, 1, 1, 1, 2
7 3, 3, 1
8 3, 3, 2
9 2, 2, 2, 2, 1
... ...

Data Structures Through C / Lecture 06 2


Digit Analysis
Each identifier is interpreted as a no. using some radix r
Same radix is used for other identifiers
Digits in each identifier is examined
Digits with skewed distribution are deleted
Digits are deleted till balance digits are in range of HT

More Hashing
Hash table contains buckets
Each buckets may contain several slots
Each slot can hold one record
Collision - when two identifiers hash into same bucket
Overflow - when new identifier is hashed into a full bucket
If number of slots = 1 then Collision = Overflow
Collision handling techniques:
Linear probing -
search the bucket ( f ( x ) + i ) % b, for 0 <= i <= b - 1
Quadratic probing -
search the bucket f ( x )
( f ( x ) + i2 ) % b
( f ( x ) - i2 ) % b, for 1 <= i <= ( b - 1) / 2

Linear Probing
4028 2133 1098 7915 6749 5141 3138 f ( x ) = no. % 10
key = ( f( x ) + i ) % b
f ( int no, int *arr, int b )
{ 0 6749
int i, j, initialpos ; 1 5141
j = no % 10 ; intialpos = j ; 2 3138
for ( i = 1 ; arr[ j ] != no && arr[ j ] != 0 ; i + + ) 3 2133
{ 4
j = ( no % 10 + i ) % b ;
if ( j == initialpos ) 5 7915
{ 6
printf ( "Array full" ) ; return ; 7
} 8 4028
} 9 1098
arr [ j ] = no ;
}

Data Structures Through C / Lecture 06 3


Quadratic Probing
4028 2133 1098 7915 6748 5141 3138

f ( x ) = no. % 10 0
key = f( x ) 1 5141
= f( x ) + i2 ) % b 2 3138
= f( x ) - i2 ) % b 3 2133
for 1 <= i <= ( b -1 ) / 2 4
5 7915
6
7 6748
8 4028
9 1098

Data Structures Through C / Lecture 06 4


Sorting
Yashavant Kanetkar

Objectives

Selection Sort and its Analysis


Bubble Sort and its Analysis
Radix Sort

main( )
Selection Sort
{ 17 6 13 12 2 i j
int a[ ] = { 17, 6, 13,12, 2 } ; 6 17 13 12 2 0-1
int i, j, t ; 6 17 13 12 2 0-2
for ( i = 0 ; i <= 3 ; i + + ) 6 17 13 12 2 0-3
{ 2 17 13 12 6 0-4
for ( j = i + 1 ; j <= 4 ; j + + ) 2 13 17 12 6 1-2
{ 2 12 17 13 6 1-3
if ( a[ i ] >a[ j ] )
2 6 17 13 12 1-4
{
t = a[ i ] ; a[ i ] = a[ j ] ; 2 6 13 17 12 2-3
a[ j ] = t ; 2 6 12 17 13 2-4
}
}
2 6 12 13 17 3 - 4
}
for ( i = 0 ; i <= 4 ; i + + )
printf ( "%d", a[ i ] ) ;
}

Data Structures Through C / Lecture 07 1


Analysis Of Selection Sort
selectionsort ( int *a, int n )
{
17, 6, 13, 12, 2
for ( i = 0 ; i < n - 1 ; i + + )
{ i No. of comp.
for ( j = i + 1 ; j < n ; j + + )
{ 0 4
if ( a[ i ] > a[ j ] ) 1 3
{ 2 2
t = a[ i ] ; 3 1
a[ i ] = a[ j ] ;
a[ j ] = t ; N-1
i N(N-1)
} =
} 2
i=1
}
} = O ( N2 )

main( ) Bubble Sort


{
17 6 13 12 2 i i+1
int a[ ] = { 17, 6, 13, 12, 2 } ; 6 17 13 12 2 0-1
int i, j, t ; 6 13 17 12 2 1-2
for ( j = 0 ; j <= 3 ; j + + ) 6 13 12 17 2 2-3
{ 6 13 12 2 17 3-4
for ( i = 0 ; i <= 3 - j ; i + + )
{ 6 13 12 2 17 0 - 1
if ( a[ i ] > a[ i + 1 ] ) 6 12 13 2 17 1 - 2
{ 6 12 2 13 17 2 - 3
t = a[ i ] ; a[ i ] = a[ i + 1 ] ; 6 12 2 13 17 0 - 1
a[ i + 1 ] = t ; 6 2 12 13 17 1 - 2
}
}
} 2 6 12 13 17 0 - 1
for ( i = 0 ; i <= 4 ; i + + )
printf ( "%d", a[ i ] ) ;
}

Analysis Of Bubble Sort


bubblesort ( int *a, int n )
{
17, 6, 13, 12, 2
for ( j = 0 ; j < n - 1 ; j + + )
{ j No. of comp.
for ( i = 0 ; i < ( n - 1 ) - j ; i + + )
{ 0 4
if ( a[ i ] > a[ i + 1 ] ) 1 3
{ 2 2
t = a[ i ] ; 3 1
a[ i ] = a[ i + 1 ] ;
a[ i + 1 ] = t ; N-1
N(N-1)
} i =
} 2
i=1
}
} = O ( N2 )

Data Structures Through C / Lecture 07 2


Radix Sort
9 47 21 32 5 13 27 4 54 76 29 85 98 62 30
Q0 30 Add elements in Q0 4 5 9
respective Q.
Q1 21 Q1 13
Initially, w.r.t units
Q2 32 62 place then w.r.t tens Q2 21 27 29
place and so on....
Q3 13 Q3 30 32
30 21 32 62 13
Q4 4 54 4 54 5 85 76 Q4 47
Q5 5 85 47 27 98 9 29 Q5 54
Q6 76 Q6 62
Q7 47 27 Q7 76
Q8 98 Q8 85
Q9 9 29 Q9 98
4 5 9 13 21 27 29 30 32 47 54 62 76 85 98

Program
main( ) initq ( int arr[ 10 ][ 3 ] )
{ {
int a[ ] = { 9, 47, 21, 32, 5, int i, j ;
13, 27, 4, 54, 76 } ; for ( i = 0 ; i < 10 ; i + + )
int arr[ 10 ][ 3 ], k, dig ; {
dig = 1 ; for ( j = 0 ; j < 3 ; j + + )
for ( k = 0 ; k <= 1 ; k + + ) arr[ i ][ j ] = 0 ;
{ }
initq ( arr ) ; }
radix ( a, arr, 10, dig ) ;
combine ( a, arr ) ;
dig *= 10 ;
}
for ( i = 0 ; i < 10 ; i + + )
printf ( "%d", a [ i ] ) ;
}
Contd...

...Contd.
radix ( int a[ ], int arr[ ][ 3], combine ( int *a, int arr[ ][ 3 ] )
int n, int dig ) {
{ int i, j, x = 0 ;
int i, j, key ; for ( i = 0 ; i < 10 ; i + + )
for ( i = 0 ; i < n ; i + + ) {
{ for ( j = 0 ; j < 3 ; j + + )
key = ( a [ i ] / dig ) % 10 ; {
for ( j = 0 ; j < 3 ; j + + ) if ( arr[ i ][ j ] ! = 0 )
{
{
a[ x ] = arr[ i ][ j ] ;
if ( arr[ key ][ j ] == 0 )
x++;
{
}
arr[ key ][ j ] = arr[ i ] ;
}
break ;
}
}
}
}
}
}

Data Structures Through C / Lecture 07 3


Sorting & Recursion
Yashavant Kanetkar

Objectives

Insertion Sort
Recursive Functions

main( ) Insertion Sort


{
int a[ ] = { 10, 12, 18, 19, 24, 2 } ; for ( i = 0 ; i <= 5 ; i ++ )
int i, j, k, t ; printf ( "%d\t", a[ i ] ) ;
for ( i = 1 ; i <= 5 ; i ++ ) }
{
t = a[ i ] ; a[0] a[1] a[2] a[3] a[4] a[5]
for ( j = 0 ; j < i ; j++ )
{
if ( t < a[ j ] ) t
{
for ( k = i ; k >= j ; k-- ) a[0] a[1] a[2] a[3] a[4] a[5]
a[ k ] = a[k - 1] ;
a[ j ] = t ;
break ;
} a[0] a[1] a[2] a[3] a[4] a[5]
}
}

Data Structures Through C / Lecture 08 1


Simple Form
main( )
{
printf ( ”Hi” ) ;
main( ) ;
}

One More Form


main( )
{
f( ) ;
}
f( )
{
printf ( ”Hi” ) ;
f( ) ;
}

main( )
More General
31698
{
int num, sum ;
d5
printf ( ”Enter a number” ) ;
scanf ( ”%d”, &num ) ; 485
sum = sumdig ( num ) ; d3
d3
printf ( ”%d”, sum ) ;
}
sumdig ( int n ) n s d
{ 327 0 7
int d ; int s = 0 ; 32 7 2
while ( n != 0 ) 3 9 3
{ 0 12
d = n % 10 ;
n = n / 10 ; s = s + d ;
}
return ( s ) ;
}

main( )
{
int num, sum ;
printf ( ”Enter a number” ) ;
scanf ( ”%d”, &num ) ;
sum = rsum ( num ) ;
printf ( ”%d”, sum ) ;
}
rsum ( int n )
{ 4!
int d ; int s ;
if ( n != 0 ) 4*3*2*1
{ 4*3!
d = n % 10 ; n = n / 10 ;
s = d + rsum ( n ) ; 3*2!
}
else 2*1!
return ( 0 ) ;
} return (s);

Data Structures Through C / Lecture 08 2


rsum ( int n ) rsum ( int n )
{ {
if ( n != 0 ) if ( n != 0 )
{ {
d = 327 % 10 ; d = 3 % 10 ;
n = 327 / 10 ; n = 3 / 10 ;
s = 7 + rsum ( 32 ) ; s = 3 + rsum ( 0 ) ;
} }
else else
return ( 0 ) ; return ( 0 ) ;
return ( s ) ; return ( s ) ;
} }
rsum ( int n ) rsum ( int n )
{ {
if ( n != 0 ) if ( n != 0 )
{ {
d = 32 % 10 ; d=
n = 32 / 10 ; n=
s = 2 + rsum ( 3 ) ; s=
} }
else else
return ( 0 ) ; return ( 0 ) ;
return ( s ) ; return ( s ) ;
} }

Recursive Factorial
main( ) Recursion Tips
{
int num, fact ;
Make recursive call in an if
printf ( ”Enter no.” ) ;
scanf ( ”%d”, &num ) ; else block is escape route
fact = refact ( num ) ; else contains end cond. logic
printf ( ”%d”, fact ) ;
return may not be present
}
refact ( int n )
{
int p ;
if ( n != 0 )
p = n * refact ( n - 1 ) ;
else
return ( 1 ) ;
return ( p ) ;
}

Data Structures Through C / Lecture 08 3


Quick Sort
Yashavant Kanetkar

Objectives

Splitting mechanism in quick sort


Quick sort algorithm
Quick sort program

11 2 9 13 57 25 17 1 90 3 Split Array
11 2 9 13 57 25 17 1 90 3

11 2 9 13 57 25 17 1 90 3

11 2 9 13 57 25 17 1 90 3

11 2 9 3 57 25 17 1 90 13

11 2 9 3 57 25 17 1 90 13

11 2 9 3 1 25 17 57 90 13

11 2 9 3 1 25 17 57 90 13

1 2 9 3 11 25 17 57 90 13

Data Structures Through C / Lecture 09 1


void quicksort ( int *, int, int ) ;
int split ( int *, int, int ) ;
Quick Sort
main( )
{
int arr[ 10 ] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i ;
quicksort ( arr, 0, 9 ) ;
for ( i = 0 ; i <= 9 ; i++ )
printf ( "%d\t", arr[ i ] ) ;
}
void quicksort ( int *a, int lower, int upper )
{
int i ;
if ( upper > lower )
{
i = split ( a, lower, upper ) ;
quicksort ( a, lower, i - 1 ) ;
quicksort ( a, i + 1, upper ) ;
}
} Cont…

..Contd 11 2 9 13 57 25 17 1 90 3 p - L to R
q - R to L
int split ( int a[ ], int lower, int upper ) if ( p < q )
{ {
int i, p, q, t ; t = a[ p ] ;
p = lower + 1 ; a[ p ] = a[ q ] ;
q = upper ; a[ q ] = t ;
i = a[ lower ] ; }
}
while ( p <= q ) t = a[ lower ] ;
{ a[ lower ] = a[ q ] ;
while ( a[ p ] < i ) a[ q ] = t ;
p++; return q ;
while ( a[ q ] > i ) }
q--;
11 2 9 3 1 25 17 57 90 13

1 2 9 3 11 25 17 57 90 13

Problem
Show the steps for sorting the following numbers using
Quick Sort Algorithm

[ 42, 23, 74, 11, 65, 58, 94, 36, 99, 87 ]

Data Structures Through C / Lecture 09 2


Wrtie the steps for quick
Exercise sort of following elements:
[ 43, 23, 74, 11, 65, 58, 94, 36, 99, 87 ]
p q
43 23 74 11 65 58 94 36 99 87
p q
43 23 74 11 65 58 94 36 99 87
p q
43 23 74 11 65 58 94 36 99 87
p q
43 23 36 11 65 58 94 74 99 87
p q
43 23 36 11 65 58 94 74 99 87
pq
43 23 36 11 65 58 94 74 99 87
q p
43 23 36 11 65 58 94 74 99 87
Contd...

Contd… q p
43 23 36 11 65 58 94 74 99 87

11 23 36 43 65 58 94 74 99 87
p q p q
11 23 36 43 65 58 94 74 99 87
pq p q
11 23 36 43 65 58 94 74 99 87
q p p q
11 23 36 43 65 58 94 74 99 87
pq
11 23 36 43 65 58 94 74 99 87
q p
65 58 94 74 99 87

58 65 94 74 99 87

Complexity
Algorithm Worst Case Best Case
Bubble sort O (n2) O (n2)
Selection Sort O (n2) O (n2)
Quick Sort O (n2) log2 n
Insertion sort O (n2) n–1
Binary Tree Sort O (n2) O (n log n)
Heap Sort O (n log n) O (n log n)
Merge Sort O (n log n) O (n log n)

Data Structures Through C / Lecture 09 3


Structures
Yashavant Kanetkar

Objectives

Defining and using structures


Creating an array of structures
How to copy one structure variable into another
Using nested structures
Passing structure elements
Passing structures

Handling Data
main( )
{
char n[ ] = { ’A’, ’X’, ’Y’, ’\0’ } ;
int a[ ] = { 23, 27, 28 } ;
float s[ ] = { 4000.50, 5000.00, 6000.75 } ;
int i ;
for ( i = 0 ; i <= 2 ; i ++ )
printf ( "%c %d %f", n[ i ], a[ i ], s[ i ] ) ;
}

Data Structures Through C / Lecture 10 1


main( ) Structures
{
struct employee
{
.structure
char n ; operators
int a ;
float s ;
};
struct employee e 1 = { ’A’, 23, 4000.50 } ;
struct employee e2 = { ’X’, 27, 5000.00 } ;
struct employee e3 = { ’Y’, 28, 6000.75 } ;
printf ( "%c %d %f", e1. n, e1. a, e1. s ) ;
printf ( "%c %d %f", e2.n, e2.a, e2.s ) ;
printf ( "%c %d %f", e3.n, e3.a, e3.s ) ;
}

main( )
{
Array of Structures
struct employee
{
char n ;
int a ;
float s ;
};
struct employee e[ ] = {
{ ’A’, 23, 4000.50 } ,
{ ’X’, 27, 5000.00 } ,
{ ’Y’, 28, 6000.75 }
};
int i ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "%c %d %f", e[ i ] .n, e[ i ].a, e[ i ].s ) ;
}

Terminology
Structure
Keyword struct employee name/tag
{
char n ; Structure
int a ; elements/
members
float s ;
};
struct employee e1, e2, e[ 10 ] ;

Structure
variables Array of
structures

Data Structures Through C / Lecture 10 2


Conclusion
A structure is usually a collection of
dissimilar elements.
Structure elements are always stored in
adjacent memory locations.

struct employee e[ 3 ] = { .. } ;
A 23 400.50 X 27 500.00 Y 28 600.75
401 408 415

Array of Structures
A 23 400.50 X 27 500.00 Y 28 600.75
401 408 415
struct employee e[ ] = { ... } ;
Ptr. to structure
char *p ;
struct employee *q ;
struct employee (*r )[ 3 ] ; Ptr. to array of structures

p=e ; q=e ; r=e ; 402 struct employee *z[3] ;


p++ ; q++ ; r++ ;
printf ( "%u", p ) ; 408
printf ( "%u", q ) ; Array of Ptrs to structures
printf ( "%u", r ) ; 422

e1
Copying Rahul 23 400.50

main( ) e2
{ Rahul 23 400.50
struct emp
{ e3
char n[20] ;
int a ; Rahul 23 400.50
float s ;
};
struct emp e1 = { "Rahul", 23, 4000.50 } ;
piecemeal
copying struct emp e2, e3 ;
e2.n = e1.n ; strcpy ( e2.n, e1.n) ;
e2.a = e1.a ;
e2.s = e1.s ; copying at
one shot
e3 = e1 ;
printf ( "%s %d %f", e3.n, e3.a, e3.s ) ;
}

Data Structures Through C / Lecture 10 3


Nested Structures
main( )
{ e
struct address
{ a
char city[20] ;
long int pin ; Rahul 23 Ngp 44010 400.50
};
struct emp
{
char n[20] ; int age ;
struct address a ; float s ;
};
struct emp e={ "Rahul", 23, "Ngp", 44010, 4000.50 } ;
printf ( "%s %d %s %ld %f", e.n, e.age, e.city, e.pin,
e.s ) ;
} e.a.city a.city
e.a.pin
printf ( ”%d”, a.b.c.d.e.f ) ; f - int

Passing Structure Elements


main( ) b
{ Basic 425 135.00
struct book 501 521 523
{
char n[20] ; int nop ; float pr ;
};
struct book b = { "Basic", 425, 135.00 } ;
display (b.n, b.nop, b.pr ) ;
show ( b.n, &b.nop, b.pr ) ;
}
display ( char *n, int pg, float p )
{
printf ( "%s %d %f", n, pg, p ) ;
}
show ( char *n, int *pg, float *p )
{
printf ( "%s %d %f", n, *pg, *p ) ;
}

Passing Structures b
Basic 425 135.00
main( )
{ 501 521 523
struct book
{
char n[20] ; int nop ; float pr ;
};
struct book b = { "Basic", 425, 135.00 } ;
display1 ( b ) ; show1 ( &b ) ;
}
display1 (struct book bb )
{
printf ("%s %d %f", bb.n, bb.nop, bb.pr ) ;
}
show1 ( struct book *bb )
{
printf ( "%s %d %f", ( * bb ) .n,( * bb ) .nop, ( * bb ) .pr );
printf ( "%s %d %f", bb -> n, bb -> nop, bb -> pr ) ;
}

Data Structures Through C / Lecture 10 4


Two Dimensional
Arrays
Yashavant Kanetkar

Objectives

Declaring and using two dimensional arrays


How to write a program to find the saddle point

main( )
Two Dimensional Array
{
int a[ ][ 5 ] = {
{ 2, 6, 1, 8, 4 } ,
optional { 1, 2, 5, 6, 8 },
optional
compulsory { 7, 9, 8, 7, 21 },
{ 4, 5, 6, 8, 10 } int b[ ][1][2][3]
};
int i, j ;
printf ( "%d", a[ 2 ][ 4 ] ) ; compulsory
printf ( "%d %d", sizeof ( a ), a ) ;
for ( i = 0 ; i <= 3 ; i + + )
{
for ( j = 0 ; j <= 4 ; j + + )
printf ( "%d", a [ i ][ j ] ) ;
printf ( ”\n” ) ;
}
}

Data Structures Through C / Lecture 12 1


main( )
{
Saddle Point
int a[ ][ 5 ] = { big = small ;
5, 2, 2, 6, 5, for ( r = 0 ; r <= 4 ; r++ )
4, 9, 3, 4, 8, {
9, 4, 2, 1, 9, if ( a[ r ][ col ] > big )
7, 1, 0, 8, 7, {
6, 2, 1, 5, 9 big = a[ r ][ col ] ;
}; row = r ;
for ( i = 0 ; i <= 4 ; i++ ) }
{ }
small = a[ i ][ 0 ] ; if ( big == small )
for ( j = 0 ; j <= 4 ; j++)
{
{
if ( a[ i ][ j ] < small ) printf ( "%d", big ) ;
{ printf ( "%d %d", row, col );
small = a[ i ][ j ] ; break ;
col = j ; }
} }
Define variables
} }

Problem
Given 2 matrices A & B of the order ( n x n )
Upper triangle = 0, Lower triangle = Non-zero
Generate C of n x ( n + 1 ) t o accommodate A and B
A C B C
a[ 4 ][ 4 ]
0, 0 0, 0 0, 0 0, 1
1 0 0 0 1, 0 1, 0 1, 0 0, 2
5 2 0 0 2, 0 2, 0 2, 0 0, 3
6 7 3 0 3, 0 3, 0 3, 0 0, 4
1 11 15 16 18
8 9 10 4 1, 1 1, 1 1, 1 1, 2
5 2 12 17 19
2, 1 2, 1 2, 1 1, 3
6 7 3 13 20
11 0 0 0 3, 1 3, 1 3, 1 1, 4
8 9 10 4 14
15 12 0 0 2, 2 2, 2 2, 2 2, 3
16 17 13 0 c[ 4 ][ 5 ] 3, 2 3, 2 3, 2 2, 4
18 19 20 14 3, 3 3, 3 3, 3 3, 4
b[ 4 ][ 4 ]

main( ) A C B C
{ 0, 0 0, 0 0, 0 0, 1
int a[ ][ 4 ] = {
1, 0, 0, 0, 1, 0 1, 0 1, 0 0, 2
5, 2, 0, 0, 2, 0 2, 0 2, 0 0, 3
6, 7, 3, 0, 3, 0 3, 0 3, 0 0, 4
8, 9, 10, 4 1, 1 1, 1 1, 1 1, 2
};
int b[ ][ 4 ] = { 2, 1 2, 1 2, 1 1, 3
11, 0, 0, 0, 3, 1 3, 1 3, 1 1, 4
15, 12, 0, 0, 2, 2 2, 2 2, 2 2, 3
16, 17, 13, 0, 3, 2 3, 2 3, 2 2, 4
18, 19, 20, 14
}; 3, 3 3, 3 3, 3 3, 4
int c[ 4 ][ 5 ], i, j ; for ( i = 0 ; i <= 3 ; i ++ )
for ( j = 0 ; j <= 3 ; j++ ) {
{ for ( j = i + 1 ; j <= 4 ; j++ )
for ( i = j ; i <= 3 ; i++ ) c[ i ][ j ] = b[ j - 1 ][ i ] ;
c[ i ][ j ] = a[ i ][ j ] ; }
} Cont…

Data Structures Through C / Lecture 12 2


Cont…

for ( i = 0 ; i <= 3 ; i ++ )
{
for ( j = 0 ; j <= 4 ; j++ )
printf ( "%d ", c[ i ][ j ] ) ;
printf ( "\n" ) ;
}
}

Determine
Determine values of a[ i ][ j ] and b[ i ][ j ] from matrix c

Determine a[ i ][ j ] Determine b[ i ][ j ]
if ( j > i ) if ( j > i )
element = 0 ; element = 0 ;
else else
element = c[ i ] [ j ] ; element = c[ j ] [ i + 1 ] ;
a[ 3 ][ 2 ] = c[ 3 ][ 2 ] b[ 3 ][ 2 ] = c[ 2 ][ 4 ]

1 0 0 0 11 0 0 0 1 11 15 16 18
5 2 0 0 15 12 0 0 5 2 12 17 19
6 7 3 0 16 17 13 0 6 7 3 13 20
8 9 10 4 18 19 20 14 8 9 10 4 14

4x4 4x4 4x5

Problem
A magic square of 4 rows x 4 columns contains different
elements. Write a function to verify whether the sum of
each individual column elements, sum of each individual
row elements and sum of diagonal elements is equal or
not.

16 3 2 13
5 10 11 8
9 6 7 12 34
4 15 14 1

Data Structures Through C / Lecture 12 3


Sparse Matrices
Yashavant Kanetkar

Objectives

Sparse matrices
How to pass arrays
Performing 3 tuple conversion

Sparse Matrices
r c Non-zero
15 0 0 22 0 -15 6 6 8
0 11 3 0 0 0 0 0 15
0 0 0 -6 0 0 0 3 22
0 0 0 0 0 0 0 5 -15
91 0 0 0 0 0 1 1 11
0 0 28 0 0 0 1 2 3
2 3 -6
4 0 91
3-Tuple Form 5 2 28

Data Structures Through C / Lecture 13 1


Passing Arrays
main( ) fun2 ( int *pa, int r, int c )
{ {
int a[ ][ 4 ] = { General
int i, j ;
1, 0, 3, 8,
5, 2, 0, 7 for ( i = 0 ; i < r ; i++ )
}; {
for ( j = 0 ; j < c ; j++ )
fun1 ( a, 4, 5 ) ;
fun2 ( a, 4, 5 ) ; {
} printf ( "%d", *pa ) ;
fun1 ( int ( *p )[ 4 ], int r, int c ) pa++ ;
{ }
int i, j ; }
}
for ( i = 0 ; i < r ; i++ )
{ a[ ]
for ( j = 0 ; j < c ; j++ ) 1 0 3 8 5 2 0 7
printf ( "%d", p[ i ][ j ] ) ;
} p[ 1 ][ 3 ] *(*(p+1)+3)
}

3-Tuple Conversion
# include <alloc.h> r c Non-zero
main( )
{ 3 4 6
int a[ 3 ][ 4 ] = { 0 0 4
4, 0, 0, 1,
2, 0, 0, 9, 0 3 1
6, 1, 0, 0 1 0 2
}; 1 3 9
int *ta ; 2 0 6
ta = create ( a, 3, 4 ) ; 2 1 1
display ( ta ) ;
free ( ta ) ;
}

Cont… for ( i = 0 ; i < r ; i++ )


{
int * create ( int *pa, int r, int c )
for ( j = 0 ; j < c ; j++ )
{
{
int rows, *p, i, j, k ; if ( *pa != 0 )
rows = count ( pa, r, c ) + 1 ; {
p = ( int * ) malloc ( rows * p[ k ] = i ; k++ ;
3 * sizeof ( int ) ) ; p[ k ] = j ; k++ ;
p[ k ] = *pa ; k++ ;
p[ 0 ] = r ; p[ 1 ] = c ;
p[ 2 ] = rows - 1; k = 3 ; }
pa ++ ;
pa }
}
return p ;
4 0 0 1 2 0 0 9 6 1 0 0 }
p
3 4 6 0 0 4 0 3 1 1 0 2 1 3 9 2 0 6 2 1 1

Data Structures Through C / Lecture 13 2


Cont…

int count ( int *pa, int r, int c )


{
int count = 0, i, j ;
for ( i = 0 ; i < r ; i++ )
{
for ( j = 0 ; j < c ; j++ )
{
if ( *pa != 0 ) pa
count ++ ;
4 0 0 1 2 0 0 9 6 1 0 0
pa++ ;
}
}
return count ;
}

Cont…

void display ( int *p )


{
int i, rows ;
rows = p[ 2 ] + 1 ;
for ( i = 0 ; i < rows * 3 ; i++ )
{
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", p[ i ] ) ;
}
}

p
3 4 6 0 0 4 0 3 1 1 0 2 1 3 9 2 0 6 2 1 1

Data Structures Through C / Lecture 13 3


Transpose of
Sparse Matrices
Yashavant Kanetkar

Objectives

How to get the transpose of a sparse matrix

Transpose
4 0 0 3 4 3 0 11 12
3 0 0 1 0 0 0 0 0
0 0 2 5 0 0 2 0 0
11 0 0 0 3 1 5 0 1
12 0 0 1

4 5 9
5 4 9
0 0 4 0 0 4
0 3 3 0 1 3 Hint
1 0 3 0 3 11
1 3 1 Search for 0, 1, 2, etc. in
2 2 2 0 4 12 first column of matrix A
2 3 5 2 2 2 and then set matrix B
3 0 11 3 0 3
4 0 12 3 1 1
4 3 1 3 2 5
3 4 1

Data Structures Through C / Lecture 14 1


Program - Transpose
#include <alloc.h> display ( tb ) ;
main( ) free ( ta ) ;
{ free ( tb ) ;
int a[ 5 ][ 4 ] = { }
4, 0, 0, 3,
3, 0, 0, 1, 5 4 9 4 5 9
0, 0, 2, 5, 0 0 4 0 0 4
11, 0, 0, 0, 0 3 3 0 1 3
12, 0, 0, 1 1 0 3 0 3 11
};
int *ta , *tb ; 1 3 1 0 4 12
ta = create ( a, 5, 4 ) ; 2 2 2 2 2 2
tb = transpose ( ta ) ; 2 3 5 3 0 3
3 0 11 3 1 1
4 0 12 3 2 5
4 3 1 3 4 1

int * transpose ( int *ta ) tb[ 0 ] = cols = ta[ 1 ] ;


{ tb[ 1 ] = ta[ 0 ] ;
int rows, c, nz, p, q, cols ; tb[ 2 ] = nz = ta[ 2 ] ;
int *tb ; q=1;
rows = ta[ 2 ] + 1 ;
for (c = 0 ; c < cols ; c++ )
tb = ( int * ) malloc ( rows *
{
3 * sizeof ( int ) ) ;
for ( p = 1; p <= nz; p++)
5 4 9 4 5 9 {
0 0 4 0 0 4 if ( ta[ p * 3 + 1 ] == c )
0 3 3 0 1 3 {
1 0 3 0 3 11 tb[ q*3 ] = ta[ p*3+1 ] ;
tb[ q*3+1 ] = ta[ p*3 ] ;
1 3 1 0 4 12 tb[ q*3+2 ] = ta[ p*3+2 ];
2 2 2 2 2 2 q++ ;
2 3 5 3 0 3 }
3 0 11 3 1 1 }
}
4 0 12 3 2 5
return tb ;
4 3 1 3 4 1 }

Problem
Write a program to verify whether transpose of a give
sparse matrix is same as the original sparse matrix.

Data Structures Through C / Lecture 14 2


Addition of
Sparse Matrices
Yashavant Kanetkar

Objectives

How to perform addition of two sparse matrices

Addition of SM
4 0 0 3 7 0 0 0 11 0 0 3
3 0 0 1 0 2 1 0 3 2 1 1
0 0 2 5 + 0 5 0 2 = 0 5 2 2
11 0 0 0 0 0 0 0 11 0 0 0
12 0 0 1 1 0 0 0 13 0 0 1

5 4 9 5 4 6 5 4 12
0 0 11
0 0 4 0 0 7 0 3 3
0 3 3 1 1 2 1 0 3
1 0 3 + 1 2 1 = 1 1 2
1 3 1 2 1 5 1 2 1
2 2 2 2 3 2 1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 3 0 11
4 0 13
4 3 1

Data Structures Through C / Lecture 15 1


5 4 9 5 4 6 5 4 12 Tips
0 0 4 0 0 7 0 0 11
0 3 3 1 1 2 0 3 3
1 0 3 + 1 2 1 = 1 0 3
1 3 1 2 1 5 1 1 2
2 2 2 2 3 2 1 2 1
1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 3 0 11
4 0 13
4 3 1

Rows in C = Rows in A + Rows in B - Sometimes


True
Row of A < Row of B - Copy from A
Row of B < Row of A - Copy from B
Row A = Row B Check columns

Addition of SM
# include <alloc.h> int *ta, *tb, *tc ;
main( ) ta = create ( a, 5, 4 ) ;
{ tb = create ( b, 5, 4 ) ;
int a[ 5 ][ 4 ] = { tc = add ( ta, tb ) ;
4, 0, 0, 3, display ( tc ) ;
3, 0, 0, 1, free ( ta ) ;
0, 0, 2, 5, free ( tb ) ;
11, 0, 0, 0, free ( tc ) ;
12, 0, 0, 1 }
};
5 4 9 5 4 6
int b[ 5 ][ 4 ] = {
0 0 4 0 0 7
7, 0, 0, 0, 0 3 3 1 1 2
0, 2, 1, 0, 1 0 3 + 1 2 1
0, 5, 0, 2, 1 3 1 2 1 5
0, 0, 0, 0 2 2 2 2 3 2
1, 0, 0, 0 2 3 5 4 0 1
}; .. .. ..

int * add ( int *s1, int *s2 ) else


{ rowa = cola = BIGNUM ;
int *p, i, j, k ; #define BIGNUM 100
int max, maxa, maxb ; if ( j <= maxb )
int rowa, cola, vala ; {
int rowb, colb, valb ; rowb = s2[ j * 3 + 0 ] ;
colb = s2[ j * 3 + 1 ] ;
maxa = s1[ 2 ] ; maxb = s2[ 2 ] ;
valb = s2[ j * 3 + 2 ] ;
max = maxa + maxb + 1 ;
}
p = ( int * ) malloc ( max * 3 * else
sizeof (int) ) ; rowb = colb = BIGNUM ;
i=j=k=1;
while ( k <= max ) 5 4 9 5 4 6
{ 0 0 4 0 0 7
if ( i <= maxa ) 0 3 3 1 1 2
{ 1 0 3 + 1 2 1
rowa = s1[ i * 3 + 0 ] ; 1 3 1 2 1 5
cola = s1[ i * 3 + 1 ] ; 2 2 2 2 3 2
vala = s1[ i * 3 + 2 ] ; 2 3 5 4 0 1
} .. .. ..

Data Structures Through C / Lecture 15 2


Cont… if ( rowa > rowb )
if ( rowa < rowb ) {
{ p[ k * 3 + 0 ] = rowb ;
p[ k * 3 + 0 ] = rowa ; p[ k * 3 + 1 ] = colb ;
p[ k * 3 + 1 ] = cola ; p[ k * 3 + 2 ] = valb ;
p[ k * 3 + 2 ] = vala ; j++ ;
i++ ; }
}
5 4 9 5 4 6 5 4 12
0 0 4 0 0 7 0 0 11
0 3 3 1 1 2 0 3 3
1 0 3 + 1 2 1 = 1 0 3
1 3 1 2 1 5 1 1 2
2 2 2 2 3 2 1 2 1
1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 .. ..Cont…
..

Cont… if ( cola > colb )


{
if ( rowa == rowb )
{ p[ k * 3 + 0 ] = rowb ;
if ( cola == colb ) p[ k * 3 + 1 ] = colb ;
{ p[ k * 3 + 2 ] = valb ;
p[ k*3+0 ] = rowa ; j++ ;
p[ k* 3+1 ] = cola ; }
p[ k*3+2 ] = vala + valb ; } // if
i++ ; j++ ; max- - ; k++ ;
} } // end of while loop

if ( cola < colb )


{ 5 4 9 5 4 6
p[ k * 3 + 0 ] = rowa ; 0 0 4 0 0 7
p[ k * 3 + 1 ] = cola ; 0 3 3 1 1 2
p[ k * 3 + 2 ] = vala ; 1 0 3 + 1 2 1
i++ ; 1 3 1 2 1 5
} 2 2 2 2 3 2
2 3 5 4 0 1
.. .. ..

Cont…
p[ 0 ] = s1[ 0 ] ;
p[ 1 ] = s1[ 1 ] ;
p[ 2 ] = max ;
return p ;
} // end of add( )

5 4 9 5 4 6 5 4 12
0 0 4 0 0 7 0 0 11
0 3 3 1 1 2 0 3 3
1 0 3 + 1 2 1 = 1 0 3
1 3 1 2 1 5 1 1 2
2 2 2 2 3 2 1 2 1
1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 .. ..Cont…
..

Data Structures Through C / Lecture 15 3


Multiplication of
Sparse Matrices
Yashavant Kanetkar

Objectives

Matrix multiplication
Multiplication of sparse matrices

Matrix Multiplication
4 0 0 1 1 0 4 3 ik k j i k kj
2 0 0 9 x 2 0 = 2 27 00 00 00 01
6 1 0 0 0 0 8 0 01 10 01 11
0 3 02 20 02 21
3x 4 4x 2 3x 2 03 30 03 31
10 00 10 01
for ( i = 0 ; i < 3 ; i + + )
{ 11 10 11 11
for ( j = 0 ; j < 2 ; j + + ) 12 20 12 21
{ 13 30 13 31
s=0;
for ( k = 0 ; k < 4 ; k + + ) 20 00 20 01
s = s + a[ i ][ k ] * b[ k ][ j ] ; 21 10 21 11
22 20 22 21
c[ i ][ j ] = s ;
23 30 23 31
}
}

Data Structures Through C / Lecture 16 1


Multiplication of SM
# include <alloc.h> int *ta, *tb, *tc ;
main( ) ta = create ( a, 3, 4 ) ;
{ tb = create ( b, 4, 2 ) ;
int a[ 3 ][ 4 ] = {
tc = mul ( ta, tb ) ;
4, 0, 0, 1,
2, 0, 0, 9, display ( tc ) ;
6, 1, 0, 0 free ( ta ) ;
}; free ( tb ) ;
free ( tc ) ;
int b[ 4 ][ 2 ] = { }
1, 0,
2, 0,
0, 0,
0, 3
};
Cont…

int* mul ( int *x, int *y ) s_in_x ( int *p, int i )


{ {
int *c, i , j, k, px ; int j ;
k = x[ 0 ] * y[ 1 ] + 1 ; for ( j = 1 ; j <= p[ 2 ] ; j++ )
z = ( int * ) malloc ( k * 3 * {
if ( p[ j * 3 ] == i )
sizeof ( int ) ) ;
k=1; return j ;
} 3 4 6
for ( i = 0 ; i < x[ 0 ] ; i++ ) }
{ 0 0 4
return -1 ;
for ( j = 0 ; j < y[ 1 ] ; j++ ) } 0 3 1
{ 1 0 2
px = s_in_x ( x, i ) ;
1 3 9
2 0 6
To be Continued...
2 1 1
p
3 4 6 0 0 4 0 3 1 1 0 2 1 3 9 2 0 6 2 1 1

int* mul ( int *x, int *y ) s_in_x ( int *p, int j, int colx )
{ {
/* Existing Code */ int i ;
for ( i = 0 ; i < x[ 0 ] ; i++ ) for ( i = 1 ; i <= p[ 2 ] ; i++ )
{ {
for ( j = 0 ; j < y[ 1 ] ; j++ ) if ( p[ i * 3 + 1 ] == j &&
{ p[ i * 3 ] == colx )
px = s_in_x ( x, i ) ; return i ;
if ( px != -1 ) } col X = row Y
{ return -1 ;
py = s_in_y ( y, j, }
3 4 6 4 2 3
x[ px * 3+1 ] ) ;
0 0 4 0 0 1
0 3 1 1 0 2
4 0 0 1 1 0 1 0 2 3 1 3
2 0 0 9 2 0 1 3 9
6 1 0 0 0 0 2 0 6
0 3 2 1 1

Data Structures Through C / Lecture 16 2


int* mul ( int *x, int *y ) 4 0 0 1 1 0
{
for ( i = 0 ; i < x[ 0 ] ; i++ ) 2 0 0 9 2 0
{ 6 1 0 0 0 0
for ( j = 0 ; j < y[ 1 ] ; j++ ) 0 3
{
px = s_in_x ( x, i ) ; 3 4 6 4 2 3
if ( px != -1 ) 0 0 4 0 0 1
{ 0 3 1 1 0 2
s=0;
1 0 2 3 1 3
while ( x[ px * 3 ] == i )
{ 1 3 9
py = s_in_y ( y, j, x[ px*3+1 ] ); 2 0 6
2 1 1
if ( py != -1 )
s = s + x[ px * 3 + 2 ] * y[ py * 3 + 2 ] ;
px++ ;
}
..
}

int* mul ( int *x, int *y ) if ( s != 0 )


{ {
int *z, i, j, k, px, py, s ;
z[ k * 3 + 0 ] = i ;
for ( i = 0 ; i < x[ 0 ] ; i + + ) z[ k * 3 + 1 ] = j ;
{ z[ k * 3 + 2 ] = s ;
for ( j = 0 ; j < y[ 1 ] ; j + + )
k++ ;
{
px = s_in_x ( x, i ) ; }
if ( px != -1 ) } // if
{ } // j loop
s=0; } // i loop
while ( x[ px * 3 ] == i ) z[ 0 ] = x[ 0 ] ;
{ z[ 1 ] = y[ 1 ] ;
py = s_in_y ( ... ) ; z[ 2 ] = k - 1 ;
if ( py != -1 ) return z ;
s = s + ... ; }
px++ ;
}

Data Structures Through C / Lecture 16 3


Storage
Yashavant Kanetkar

Objectives

How two dimensional arrays are stored


3-D arrays
4-Darrays
N-D arrays

Storage - 2D Array 3 x 4 matrix


a00 a01 a02 a03
a10 a11 a12 a13
a20 a21 a22 a23
Row major
a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23

int a[ 3 ][ 4 ] ; int a[ m ][ n ]
a23 aij

Col major
a00 a10 a20 a01 a11 a21 a02 a12 a22 a03 a13 a23

int a[ 3 ][ 4 ] ; int a[ m ][ n ]
a23 aij

Data Structures Through C / Lecture 17 1


3-D Array

a[ 1…u1, 1…u2, 1…u3 ] u2

u1
u3
Row major
a[ i ][ j ][ k ]

Column major
a[ i ][ j ][ k ]

4-D Array
a[ 1…u1, 1…u2, 1…u3, 1…u4 ]

Row major
a[ i ][ j ][ k ][ l ]

Column major
a[ i ][ j ][ k ][ l ]

n-Dimensional Array
a[ 1…u1, 1…u2, 1…u3, …, un ]

Row major Column major


a[ i1 ][ i2][ i3 ][ .. ][ in ] a[ i1 ][ i2][ i3 ][ .. ][ in ]

+ ( i1 – 1 ) * u2u3u4…un + ( i1 – 1 ) * u2u3u4…un
+ ( i2 – 1 ) * u3u4…un + ( i2 – 1 ) * u3u4…un
+ ( i3 – 1 ) * u4u5…un + ( i3 – 1 ) * u4u5…un
+ ( i4 – 1 ) * u5u6…un + ( i4 – 1 ) * u5u6…un
+ +
. .
. .
. .
+ ( i n - 1 – 1 ) * un + ( i n – 1 ) * un - 1
+(in–1) +( in-1–1 )

Data Structures Through C / Lecture 17 2


Problem
Find location of element A[ 6 ][ 2 ][ 3 ][ 8 ] relative to first
element of the array A[ 3:8][ 2:4][ 3:6 ][ 6:9 ]
Row major
+(6–3)*((4–2+1)*(6–3+1)*(9–6+1))
+(2–2)*((6–3+1)*(9–6+1))
+(3–3)*(9–6+1)
+ 8– 6

Col major
+(6–3)*((4–2+1)*(6–3+1)*(9–6+1))
+(2–2)*((6–3+1)*(9–6+1))
+(8–6)*(6–3+1)
+ 3– 3

Problem
Find the location of an element A[ 7 ][ 8 ][ 2 ][ 5 ] relative to
the first element of the array A[ 6:8 ][ 7:10 ][ 2:5 ][ 5:8 ]

Data Structures Through C / Lecture 17 3


Dynamic Memory
Allocation
Yashavant Kanetkar

Objectives

Limitations on arrays
Dynamic memory allocation
How the memory allocation is done

Arrays
No Flexibility
main( )
{
int m1, m2, m3, i, per [ 10 ] ;
for ( i = 0 ; i <= 9 ; i++ )
{
printf ( "Enter marks" ) ;
scanf ( "%d %d %d", &m1, &m2, &m3 ) ;
per [ i ] = ( m1 + m2 + m3 ) / 3 ;
printf ( "%d", per [ i ] ) ;
}
}

Data Structures Through C / Lecture 18 1


Dynamic Allocation
# include "alloc.h"
main( )
{
int *p ; int m1, m2, m3, i, per ;
Memory printf ( "Enter no. of students" ) ;
p scanf ( "%d", &n ) ;
malloc ( n * 2 ) ;
for ( i = 0 ; i < n ; i++ )
{
n*2 scanf ( "%d%d%d", &m1, &m2, &m3 ) ;
per = ( m1 + m2 + m3 ) / 3 ;
* ( p + i ) = per ;
}
for ( i = 0 ; i < n ; i++ )
printf ( "%d", *( p + i ) ) ;
}

Memory Allocation
Array malloc( )

Static Dynamic

Compile Time Execution Time

Variables are created only during execution


Static - Arrangement made at compilation time
- Arrangement - Offset + Instruction to create var
Dynamic - Arrangement made at execution time
- Arrangement - Call to malloc( )

int x, y ;
main( ) Allocation
{
int j ; float k ; int *p ;
p = ( int * ) malloc ( 20 ) ; Compiler
}
Symbol table entries for variables
- Name, Scope, Length
- Offset from DS (global), SS (local)
Instructions for local variables
Call to malloc( )
Creates OBJ and discards Symbol Table
Our object code + Library’s object code Linker
Create EXE file format (Header to help loader)
If too many globals - Loader fails Loader
Fatal
If too many locals - Stack overflow
If too much dynamic demand - Heap full

Data Structures Through C / Lecture 18 2


Better Still...
?
int *p[ ] ;
char ch = ’Y’ ;
while ( ch = = ’Y’ )
{
scanf ( "%d %d %d", &m1, &m2, &m3 ) ;
per = ( m1 + m2 + m3 ) / 3 ;
malloc ( 2 ) ; p p p
*p = per ;
printf ( "Another student y/n" ) ;
ch = getche( ) ;
}
Memory Leaks

Best... NULL

55 400 63 750 28 900 45 120 60


200 400 750 900 120
node

55 63 28 45 60

data link
NULL
Linked List
struct node
{
int data ;
struct node *link ;
};

Data Structures Through C / Lecture 18 3


Linked List
Yashavant Kanetkar

Objectives

What are memory leaks


What are linked lists
How to create a linked list of records

Linked List p q r s
main( )
{
struct node 55 63 28 45 N
{
int data ;
struct node *link ;
};
struct node *p , *q, *r, *s ;
malloc ( sizeof ( struct node ) ) ;
q = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
r= ...
s= ...
p data = 55 ;q data = 63 ;r data = 28 ;s data = 45
p link = q ; q link = r ; r link = s ; s link = NULL ;

Cont...

Data Structures Through C / Lecture 19 1


..Cont p q r ss
# include "alloc.h"
main( ) 55 63 28 45 N
{
...
...
... t t t
...
printf ( "%d %d %d %d", p data, q data,
r data, s data ) ;
printf ( "%d %d %d", p data, p link data,
p link link data ) ;
t=p;
while ( t != NULL )
{
printf ( "%d", t data ) ; t = t link ;
}
}

# include "alloc.h" Most General


struct node
{
int per ; struct node *link ;
};
main( )
{
struct node *p ;
char ch = ’Y’ ; int pp, m1, m2, m3 ;
p = NULL ;
while ( ch == ’Y’ )
{
scanf ( "%d %d %d", &m1, &m2, &m3 ) ;
pp = ( m1 + m2 + m3 ) / 3 ;
add ( &p, pp ) ;
printf ( "Another student y/n" ) ;
ch = getche( ) ;
}
}

add ( struct node **q, int pp )


{
struct node *r ; struct node *t ;
r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
r -> per = pp ; r -> link = NULL ;
if ( *q == NULL ) Empty linked list
*q = r ; r
else
{ 45 N
t = *q ;
while ( t -> link != NULL ) *q
t = t -> link ;
t -> link = r ;
} Non-empty linked list
} *q r

45 16 25 N 90 N

t t t

Data Structures Through C / Lecture 19 2


Variety...
55 63 28 45 60 N

1.1 0.3 1.7 3.5 2.9 N

Anil 24 Sunil 21 Anuj 22 N

struct node
{
char name[ 20 ] ;
int age ;
struct node *link ;
};

Linked List Of Records


# include "alloc.h"
struct node
{
char name [ 20 ] ; int age ; struct node *link ;
};
main( )
{
struct node *p ;
struct node t ; char ch = ’Y’ ;
p = NULL ;
while ( ch == ’Y’ )
{
printf ( "\nEnter name & age: " ) ;
scanf ( "%s%d", t.name, &t.age ) ;
add ( &p, t ) ;
printf ( "Another student Y/N" ) ;
ch = getche( ) ;
}
} Contd...

add ( struct node **q, struct node n )


{
struct node *r ; struct node *t ;
r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
*r = n ; r -> link = NULL ;
if ( *q == NULL )
Empty linked list
*q = r ;
else r
{
t = *q ; Anil 24 N
while ( t -> link != NULL )
t = t -> link ; *q
t -> link = r ;
} Non-empty linked list
}
*q r

Anil 24 Sunil 21 N Anuj 22 N

t t

Data Structures Through C / Lecture 19 3


Operations on
Linked List - I
Yashavant Kanetkar

Objectives
How to perform various operations on linked
lists
How to append a new node to a link list
How to add a new node at the beginning of a
linked list
How to add a new node at a specified position
in a linked list
How to delete a node from a linked list
How to delete all nodes in the list

#include "alloc.h"
struct node
LL Operations
{ addatbeg ( &p, 7 ) ;
int data ; addatbeg ( &p, 58 ) ;
struct node *link ; display ( p ) ;
}; addafter ( p, 7, 0 ) ;
main( ) addafter ( p, 2, 1 ) ;
addafter ( p, 5, 99 ) ;
{
struct node *p ; display ( p ) ;
c = count ( p ) ;
p = NULL ; printf ( "\nNo. of eles. %d", c ) ;
int c ;
del ( &p, 30 ) ;
append ( &p, 14 ) ; del ( &p, 10 ) ;
append ( &p, 30 ) ;
append ( &p, 25 ) ; display ( p ) ;
append ( &p, 17 ) ; c = count ( p ) ;
printf ( "\nNo. of eles. %d”, c ) ;
display ( p ) ; deleteall ( &p ) ;
}

Data Structures Through C / Lecture 20 1


append ( struct node **q, int n )
{
Append
struct node *r, *t ;
r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
r -> data = n ;
r -> link = NULL ; Empty List
if ( *q == NULL ) *q r
*q = r ;
else
{ 14 N
t = *q ;
while ( t -> link != NULL )
t = t -> link ;
t -> link = r ; Non-Empty List
} *q t t r
}

14 30 25 N 17 N

Add At Beginning
addatbeg ( struct node **q, int n )
{
struct node *t ;
t = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
t -> data = n ;
t -> link = *q ;
*q = t ;
}

t *q

7 14 30 25 N
New node

addafter ( struct node *q, int pos, int n )


{ q t t
struct node *t, *r ;
int i ;
t=q; 14 30 25 N
for ( i = 0 ; i < pos ; i++ )
{ 2
if ( t -> link == NULL )
break ; r
t = t -> link ;
}
r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
r -> data = n ;
r -> link = t -> link ;
t -> link = r ;
}

Data Structures Through C / Lecture 20 2


q

14 30 25 N

display ( struct node *q ) int count ( struct node *q )


{ {
while ( q != NULL ) int c = 0 ;
{ while ( q != NULL )
printf ( "%d\t", q->data ) ; {
q = q -> link ; q = q -> link ;
}
c++ ;
}
}
return c ;
}

del ( struct node **q, int n )


{ Node to be Deleted = 14
struct node *t , *prev ;
*q t
t = *q ;
while ( t != NULL )
{ 14 30 2 N
if ( t -> data == n )
{
if ( t == *q )
*q = t -> link ;
else
prev -> link = t -> link ; Node to be Deleted = 2
free ( t ) ; *q t
return ;
}
prev = t ; 14 30 2 25 N
t = t -> link ;
} prev
printf ( "\nEle. not found." ) ;
}

Delete All Nodes


*q t

14 30 2 N

deleteall ( struct node **q )


{
struct node *t ;
while ( *q != NULL )
{
t = *q ;
*q = ( *q ) -> link ;
free ( t ) ;
}
}

Data Structures Through C / Lecture 20 3


Operations On
Linked List II
Yashavant Kanetkar

Objectives

How to arrange the linked list elements in


ascending order
How to sorting the elements in the linked list

#include "alloc.h" Ascending Order LL


struct node
{
int data ;
struct node *link ;
};
main( )
{
struct node *p ; int c ;
p = NULL ;
add ( &p, 5 ) ;
add ( &p, 1 ) ;
add ( &p, 6 ) ;
add ( &p, 4 ) ;
add ( &p, 7 ) ;
display ( p ) ;
c = count ( p ) ;
printf ( "\nNo. of eles. %d", c ) ;
}

Data Structures Through C / Lecture 21 1


add( ) Function
add ( struct node **q, int n )
{
struct node *r, *t ;
t = *q ;
r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
r -> data = n ;
Empty LL
if ( *q == NULL || ( *q ) -> data > n )
{ *q r
*q = r ;
( *q ) -> link = t ;
} 5 N
Addition At Beginning New node
r *q t

2 4 5 6 N
Cont… New node

Cont… *q t

2 4 6 N
else
{ 5
while ( t != NULL )
{ r
if ( ( t -> data <= n && t -> link -> data > n ) ||
( t -> data <= n && t -> link == NULL ) )
{
r -> link = t -> link ; t -> link = r ;
return ;
}
t = t -> link ;
} *q t r
}
}
2 4 5 N 6 N

Sorting
#include "alloc.h" display ( p ) ;
struct node ssort ( p ) ;
{ display ( p ) ;
int data ; deleteall ( p ) ;
struct node *link ;
}
};
main( )
{
struct node *p = NULL ;
append ( &p, 17 ) ;
append ( &p, 6 ) ;
append ( &p, 13 ) ;
append ( &p, 12 ) ;
append ( &p, 2 ) ;

Data Structures Through C / Lecture 21 2


ssort ( struct node *q )
{
struct node *a , *b ;
int n, i, j, t ;
a = q ; n = count ( a ) ;
for ( i = 0 ; i < n - 1 ; i++ )
{
b = a -> link ;
for ( j = i + 1 ; j < n ; j++ )
{
if ( a -> data > b -> data )
{
t = a -> data ; a -> data = b -> data ; b -> data = t ;
}
b = b -> link ;
}
a = a -> link ; q a b
}
}
17 6 13 12 2 N

Data Structures Through C / Lecture 21 3


Operations On
Linked List - III
Yashavant Kanetkar

Objectives

How to perform various operations on linked


lists
How to reversing a linked list
How to merge two linked lists

Reversing LL

*q

7 43 3 23 5 N

7 N 43 3 23 5

Data Structures Through C / Lecture 22 1


Reversing LL
#include "alloc.h"
display ( p ) ;
struct node
reverse ( &p ) ;
{
int data ; display ( p ) ;
struct node *link ; deleteall ( p ) ;
}; }
main( )
{
struct node *p = NULL ;
append ( &p, 7 ) ;
append ( &p, 43 ) ;
append ( &p, 3 ) ;
append ( &p, 23 ) ;
append ( &p, 5 ) ;

reverse ( struct node **q )


{
struct node *r, *prev, *t ;
r = *q ; prev = NULL ;
while ( r != NULL )
{
t = prev ;
prev = r ;
r = r -> link ;
prev -> link = t ;
}
*q = prev ;
}

7 43 3 23 5 N
*q

Merging LL
f

9 12 14 17 79 N
s

12 17 24 64 87 N

9 12 12 14 17

17 24 64 79 87 N

Data Structures Through C / Lecture 22 2


Merging LLs
#include "alloc.h" add ( &s, 12 ) ;
struct node
add ( &s, 17 ) ;
{
add ( &s, 24 ) ;
int data ;
add ( &s, 64 ) ;
struct node *link ;
add ( &s, 87 ) ;
};
main( ) printf ( "\nSecond LL: " ) ;
{ display ( s ) ;
struct node *f, *s, *t ; merge ( f, s, &t ) ;
f = s = t = NULL ;
printf ( "\nMerged LL: " ) ;
add ( &f, 9 ) ;
add ( &f, 12 ) ; display ( t ) ;
add ( &f, 14 ) ; deleteall ( f ) ;
add ( &f, 17 ) ; deleteall ( s ) ;
add ( &f, 79 ) ; deleteall ( t ) ;
printf ( "First LL: " ) ; }
display ( f ) ;

merge ( struct node *p, struct node *q, struct node **s )
{ Empty List
struct node *z ;
*s z
while ( p != NULL && q != NULL )
{
if ( *s == NULL )
z = *s = ( struct node * ) malloc (
sizeof ( struct node ) ) ;
else
{
z -> link = ( struct node *) malloc (
sizeof ( struct node ) ) ;
z = z -> link ;
} Non-Empty List
*s z

14

if ( p -> data <= q -> data )


{
z -> data = p -> data ;
p = p -> link ;
}
else
{ Third List
z -> data = q -> data ;
q = q -> link ; z
}
} // while
9 12 12

First List Second List


p q

9 12 14 N 12 17 24 N

Data Structures Through C / Lecture 22 3


while ( p != NULL )
{
z -> link = ( struct node * ) malloc (
sizeof ( struct node ) ) ;
z = z -> link ;
z -> data = p -> data ;
p = p -> link ;
}
while ( q != NULL )
{
z -> link = ( struct node * ) malloc (
sizeof ( struct node ) ) ;
z = z -> link ;
Third List
z -> data = q -> data ;
q = q -> link ; z
}
z -> link = NULL ;
} // merge( ) 64 79 87 N

Data Structures Through C / Lecture 22 4


Operations On
Linked List - IV
Yashavant Kanetkar

Objectives

How to concatenate two linked lists


How to perform the addition of polynomials by
using linked lists

Concatenation Of LL
#include "alloc.h" append ( &s, 7 ) ;
struct node append ( &s, 13 ) ;
{ append ( &s, 2 ) ;
int data ; append ( &s, 84 ) ;
struct node *link ;
printf ( "\nSecond LL: " ) ;
};
display ( second ) ;
main( )
{ concat ( &f, &s ) ;
struct node *f, *s ; printf ( "\nConcatenated LL: " ) ;
f = s = NULL ; display ( f ) ;
append ( &f, 1 ) ; deleteall ( f ) ;
append ( &f, 41 ) ; deleteall ( s ) ;
append ( &f, 3 ) ; }
append ( &f, 9 ) ;
printf ( "\nFirst LL: " ) ;
display ( f ) ;

Data Structures Through C / Lecture 23 1


concat ( struct node **p,
struct node **q )
{
struct node *t ; t = *p ;
if ( *p == NULL ) while ( t -> link != NULL )
{ t = t -> link ;
*p = *q ; t -> link = *q ;
return ; }
}
if ( *q == NULL )
return ;

First List Second List


*p *q

9 12 14 N 12 17 24 N

#include "alloc.h" Polynomial Addition


struct pnode
{ pappend ( &s, 1.5, 6 ) ;
float coeff ; pappend ( &s, 2.5, 5 ) ;
int exp ; pappend ( &s, -3.5, 4 ) ;
struct pnode *link ; pappend ( &s, 4.5, 3 ) ;
}; pappend ( &s, 6.5, 1 ) ;
main( ) pdisplay ( s ) ;
{
struct pnode *f, *s, *t ; padd ( f, s, &t ) ;
f = s = t = NULL ; pdisplay ( t ) ;
pappend ( &f, 1.4, 5 ) ;
deleteall ( f ) ;
pappend ( &f, 1.5, 4 ) ; deleteall ( s ) ;
pappend ( &f, 1.7, 2 ) ; deleteall ( t ) ;
pappend ( &f, 1.8, 1 ) ; }
pappend ( &f, 1.9, 0 ) ;
pdisplay ( f ) ;

padd ( struct pnode *p, struct pnode *q, struct pnode **s )
{
struct pnode *z ;
while ( p != NULL && q != NULL )
{
if ( *s == NULL )
z = *s = ( struct pnode * ) malloc (
sizeof ( struct pnode ) ) ;
else
{
z -> link = ( struct pnode * ) malloc (
sizeof ( struct pnode ) ) ;
z = z -> link ;
}

Data Structures Through C / Lecture 23 2


if ( p -> exp == q -> exp )
{
z -> coeff = p -> coeff + q -> coeff ;
z -> exp = p -> exp ;
p = p -> link ; q = q -> link ;
}
else
{
if ( p -> exp > q -> exp )
{
*z = *p ;
p = p -> link ;
}
else
{
*z = *q ;
q = q -> link ;
}
}
} // while

while ( p != NULL )
{
z -> link = ( struct pnode * ) malloc (
sizeof ( struct pnode ) ) ;
z = z -> link ;
*z = *p ;
p = p -> link ;
}
while ( q != NULL )
{
z -> link = ( struct pnode * ) malloc (
sizeof ( struct pnode ) ) ;
z = z -> link ;
*z = *q ;
q = q -> link ;
}
z -> link = NULL ;
} // padd

Data Structures Through C / Lecture 23 3


Circular
Linked List
Yashavant Kanetkar

Objectives
What are circular linked lists
How to perform common operations on a circular
linked list
How to add a new node to a circular list
How to delete an existing node from a circular lis
How to count the nodes of the circular linked list
How to display the nodes in the circular linked lis

Circular Linked List


p

12 17 24 64 87 N

12 17 24 64 87

Data Structures Through C / Lecture 24 1


CLL Operations
#include "alloc.h" caddafter ( &p, 2, 99 ) ;
struct node caddafter ( &p, 66, 88 ) ;
{ cdisplay ( p ) ;
int data ; cdel ( &p, 15 ) ;
struct node *link ; cdel ( &p, 10 ) ;
}; cdel ( &p, 88 ) ;
main( ) cdisplay ( p ) ;
{ c = ccount ( p ) ;
struct node *p ; int c ; printf ( "\nNo. of ele. %d", c ) ;
p = NULL ;
deleteall ( &p ) ;
cappend ( &p, 10 ) ; }
cappend ( &p, 18 ) ;
caddatbeg ( &p, 5 ) ;
caddatbeg ( &p, 15 ) ;

cappend ( struct node **q, int n )


{
struct node *r , *t ;
r = ( struct node * ) malloc ( Empty List
sizeof ( struct node ) ) ; *q r
r -> data = n ;
if ( *q == NULL )
*q = r ; 17
else
{
t = *q ;
while ( t -> link != *q )
t = t -> link ; Non-Empty List
t -> link = r ; *q t t r
t
}
r -> link = *q ;
} 12 17 24 64

caddatbeg ( struct node **q, int n )


{
struct node *r, *t ;
r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
r -> data = n ; Empty List
if ( *q == NULL ) *q r
r -> link = r ;
else
{ 17
t = *q ;
while ( t -> link != *q )
t = t -> link ;
t -> link = r ; r -> link = *q ; Non-Empty List
}
r *q t t t
*q = r ;
}
64 12 17 24

Data Structures Through C / Lecture 24 2


caddafter ( struct node **q, int pos, int n )
{
struct node *t ;
int i ;
t = *q ;
for ( i = 0 ; i < pos ; i++ )
{
if ( t -> link == *q )
break ;
t = t -> link ;
}
*q t t

64 12 17 24

Cont…

Cont… r = ( struct node * ) malloc ( sizeof ( struct node ) ) ;


r -> data = n ;
r -> link = t -> link ;
t -> link = r ; Define r
} // caddafter
r
*q t 2

64 12 17 24

*q t r

12 17 24 88

cdel ( struct node **q, int n )


{
struct node *t , *f ;
Node to be Deleted = 64
t = *q ; f = NULL ;
while ( t != f ) tr *q r r
{
f = *q ;
if ( t -> data == n ) 64 12 17
{
if ( t == *q )
{
r = *q ;
while ( r -> link != *q )
r = r -> link ;
*q = r -> link = t -> link ;
free ( t ) ;
}
Cont…

Data Structures Through C / Lecture 24 3


Cont… else
{
prev -> link = t -> link ;
free ( t ) ;
}
return ;
} // if
prev = t ;
t = t -> link ;
} // while
printf ( "No. Not Found." ) ;
} // cdel
Node to be Deleted = 17
*q t t prev t

64 12 17 24
prev

deleteall ( struct node **q )


{
struct node *t, *last, *temp
t = *q ;
while ( t -> link != *q )
t = t -> link ;
last = t ;
t = *q ;
while ( t -> next != *q )
{
temp = t ;
t = t -> link ;
last -> link = *q = t
free ( temp ) ;
} *q t temp t temp t temp t temp
free ( *q ) ;
*q = NULL ;
64 12 17 24
}

q t t

64 12 17 24

cdisplay ( struct node *q ) ccount ( struct node *q )


{ {
struct node *t , *f ; struct node *t, *f ;
int c = 0 ;
t=q;
t=q;
f = NULL ;
f = NULL ;
while ( t != f ) while ( t != f )
{ {
f=q;
f = q ; c++ ;
printf ( "%d\t", t -> data ) ;
t = t -> link ;
t = t -> link ; }
}
return c ;
}
}

Data Structures Through C / Lecture 24 4


Doubly Linked
List
Yashavant Kanetkar

Objectives

What are doubly linked lists


How to perform similar common operations on
a doubly linked list

Doubly Linked List

11 2 14 17 N

N 11 2 14 17 N

struct dnode
{
struct dnode *prev ;
int data ;
struct dnode *next ;
}

Data Structures Through C / Lecture 25 1


DLL Operations
#include "alloc.h" d_display ( p ) ;
struct dnode d_addatbeg ( &p, 33 ) ;
{ d_addatbeg ( &p, 55 ) ;
struct dnode *prev ;
d_display ( p ) ;
int data ;
struct dnode *next ; d_addafter ( p, 4, 66 ) ;
}; d_addafter ( p, 2, 96 ) ;
main( ) d_display ( p ) ;
{ d_delete ( &p, 55 ) ;
struct dnode *p ; int c ; d_delete ( &p, 2 ) ;
p = NULL ; d_delete ( &p, 99 ) ;
d_append ( &p , 11 ) ; d_display ( p ) ;
d_append ( &p , 2); c = d_count ( p ) ;
d_append ( &p , 14 ) ; printf ( "\nNo. of ele. %d", c ) ;
d_append ( &p , 17 ) ;
deleteall ( &p ) ;
d_append ( &p , 99 ) ;
}

d_append ( struct dnode **q, int n )


{
struct dnode *r, *t ;
r = ( struct dnode * ) malloc ( sizeof ( struct dnode ) ) ;
r -> data = n ; r -> next = NULL ;
if ( *q == NULL ) Empty List
{ *q r
r -> prev = NULL ; *q = r ;
}
else N 11 N
{
t = *q ;
while ( t -> next != NULL )
t = t -> next ; Non-Empty List
r -> prev = t ; *q t t r
t -> next = r ;
}
} N 2 14 N 11 N

d_addatbeg ( struct dnode **q, int n )


{
struct dnode *t ;
t = ( struct dnode * ) malloc ( sizeof ( struct dnode ) ) ;
t -> prev = NULL ;
t -> data = n ;
t -> next = *q ;
( *q ) -> prev = t ;
*q = t ;
}
t *q

N 11 N 2 14 17 N

Data Structures Through C / Lecture 25 2


d_addafter ( struct dnode *q, int pos, int n )
{
int i ;
struct dnode *r ; q q
for ( i = 0 ; i < pos ; i++ )
{ N 2 14 17 N
if ( q -> link == NULL )
break ;
q = q -> next ; 11
}
r
r = ( struct dnode * ) malloc (
sizeof ( struct dnode ) ) ;
r -> data = n ;
r -> prev = q ; r -> next = q -> next ;
if ( q -> next != NULL )
q -> next -> prev = r ;
q -> next = r ; What if q points to
} last node

d_delete ( struct dnode **q, int n )


{
struct dnode *t ;
t = *q ;
while ( t != NULL )
{
if ( t -> data == n )
{
if ( t == *q )
{
*q = ( *q ) -> next ;
( *q ) -> prev = NULL ;
} Node to be Deleted = 2
t *q

N 2 N 14 11 N
Cont…

Cont… else
{
t -> prev -> next = t -> next ;
if ( t -> next != NULL )
t -> next -> prev = t -> prev ;
} Node to be Deleted = 2
free ( t ) ;
return ; t *q
} // if
t = t -> next ; N 2 N 14 11 N
} // while
printf ( "\nNo. not found." ) ;
} // d_delete Node to be Deleted = 11
*q t

N 2 14 11 17 N

Data Structures Through C / Lecture 25 3


Sparse Matrices
as Linked List I
Yashavant Kanetkar

Objectives

How sparse matrices can be represented in the


form of linked lists

SM Represented As LL
2 0 7 3 3 3
3-Tuple
0 0 2
11 0 0
0 2 7
0 0 0 1 0 11

3 3 0 N 1 2 N

0 0 0 2 0 2 7
N N

1 1 0 11
N N

N 2 N

Data Structures Through C / Lecture 26 1


Exercise
0 9 0 0 3 4 3 Find the linked
3-Tuple 0 1 9 representation of given SM
5 17 0 0
1 0 5
0 0 0 0 1 1 17

Data Structures Through C / Lecture 26 2


Sparse Matrices as
Linked List - II
Yashavant Kanetkar

Objectives

How to add a new node to the linked list


How to display the contents of the linked list
How to delete all the nodes in the linked list

struct node
Program
{ 3 3 0
int row, col, val ;
struct node *d, *r ;
}; 0 0 0 2
struct rcnode
{
int no ; 1 1 0 11
struct rcnode *p1 ; N N
struct node *p2 ;
};
N 2 N
struct spmat
{
struct rcnode *fr ;
int rows, cols ;
struct rcnode *fc ;
};

Data Structures Through C / Lecture 27 1


struct node
Program
{ #include "alloc.h"
int row, col, val ; main( )
struct node *d, *r ; {
}; struct spmat s ; int i ;
struct rcnode int tu [ 4 ] [ 3 ] = {
{ 3, 3, 3,
struct rcnode *p1 ; 0, 0, 2,
int no ; 0, 2, 7,
struct node *p2 ; 1, 0, 11
}; };
init ( &s, tu ) ;
struct spmat
{ for ( i = 1 ; i <= tu[ 0 ][ 2 ] ; i++ )
struct rcnode *fr ; add ( s, tu + i ) ;
int rows, cols ; display ( s ) ;
struct rcnode *fc ; deleteall ( &s ) ;
}; }

init ( struct spmat *p, int *ptup ) p 3 3


{
struct rcnode *t ; int i ;
t 0 N
p -> rows = ptup[ 0 ] ;
p -> cols = ptup[ 1 ] ; t 1 N
for ( i = 0 ; i < ptup[ 0 ] ; i++ )
{
t N 2 N
if ( i == 0 )
t = p -> fr = ( struct rcnode * ) malloc (
sizeof ( struct rcnode ) ) ;
else
{
t -> p1 = ( struct rcnode * ) malloc ( sizeof (
struct rcnode ) ) ;
t = t -> p1 ;
}
t -> no = i ; t -> p2 = NULL ;
}
t -> p1 = NULL ; Cont…

Cont…
for ( i = 0 ; i < ptup[ 1 ] ; i++ )
{
if ( i == 0 )
t = p -> fc = ( struct rcnode * ) malloc (
sizeof ( struct rcnode ) ) ;
else
{
t -> p1 = ( struct rcnode * ) malloc ( sizeof (
struct rcnode ) ) ;
t = t -> p1 ;
}
t -> no = i ; t -> p2 = NULL ;
}
t -> p1 = NULL ;
} // initsmll
p t t t

3 3 N 0 N 1 N 2 N

Data Structures Through C / Lecture 27 2


add ( struct spmat q, int *ptup )
{ 0 0 2
struct node *p , *t1 ;
struct rcnode *rh ; int i ; 3 3

p = ( struct node * ) malloc (


rh 0 N
sizeof ( struct node ) ) ;
p -> row = ptup[ 0 ] ; rh 1 N
p -> col = ptup[ 1 ] ;
p -> val = ptup[ 2 ] ;
rh N 2 N
rh = q.fr ;
for ( i = 0 ; i < p -> row ; i++ )
rh = rh -> p1 ;
t1 = rh -> p2 ; 3 3 N 0
if ( t1 == NULL ) p
rh -> p2 = p ; rh 0 N 0 0 2

Cont…

Cont…

3 3 0 N 1 2 N
t1 p
0 0 0 2 0 2 7
rh N N N

else
{
while ( t1 -> r != NULL )
t1 = t1 -> r ;
t1 -> r = p ;
}
p -> r = NULL ;

Cont…

Cont… Define ch
ch = q.fc ; ch
for ( i = 0 ; i < p -> col ; i++ ) 3 3 0
ch = ch -> p1 ; p
t1 = ch -> p2 ;
0 0 0 2
if ( t1 == NULL )
N
ch -> p2 = p ;
else
ch
{
while ( t1 -> d != NULL ) 3 3 0
t1 = t1 -> d ; t1
t1 -> d = p ; 0 0 0 2
} N
p -> d = NULL ;
} // addspll p
1 0 2 7
N N

Data Structures Through C / Lecture 27 3


display ( struct spmat q )
{
struct rcnode *t ;
struct node *p ;
printf ( "Row = %d, Col = %d\n", q.rows, q.cols ) ;

t = q.fr ;
3 3 0
while ( t != NULL )
{ p
p = t -> p2 ; t
0 0 0 2
while ( p != NULL ) N N
{
printf ( "%d %d %d\n", p -> row, p -> col, p -> val ) ;
p = p -> r ;
}
t = t -> p1 ;
}
}

deleteall ( struct spmat *q )


t = q -> fc ;
{
while ( t != NULL )
struct rcnode *t , *t2 ;
struct node *p, *t1 ; {
t2 = t ;
t = q -> fr ; t = t -> p1 ;
while ( t != NULL ) free ( t2 ) ;
{ }
p = t -> p2 ; q -> fr = q -> fc = NULL ;
while ( p != NULL ) }
{
t1 = p ;
p = p -> r ; q t t2
free ( t1 ) ;
3 3 0
}
t2 = t ; p t1
t = t -> p1 ; t
t2 0 0 0 2
free ( t2 ) ;
N N
}

Data Structures Through C / Lecture 27 4


Linked List Using
Recursion
Yashavant Kanetkar

Objectives

How to implement some of the linked list


operations using recursion

Recursive count( )
#include "alloc.h" int count ( struct node *q )
struct node {
{ int i ;
int data ; if ( q != NULL )
struct node *link ; {
}; i = 1 + count ( q -> link ) ;
main( ) return ( i ) ;
{ }
struct node *p ; else
int c ; return ( 0 ) ;
p = NULL ; }
append ( &p, 41 ) ;
append ( &p, 2 ) ;
append ( &p, 23 ) ; q q q q
c = count ( p ) ;
printf ( ”Ele. = %d", c ) ;
41 2 23 N
}

Data Structures Through C / Lecture 28 1


Recursive compare( )
# include "alloc.h" append ( &s, 1 ) ;
# define SAME 1 append ( &s, 2 ) ;
# define DIFF 0 append ( &s, 3 ) ;
struct node
{ if ( compare ( f, s ) == SAME )
int data ; printf ( "Equal." ) ;
struct node *link ; else
}; printf ( "Not equal." ) ;

main( ) deleteall ( &f ) ;


{ deleteall ( &s ) ;
struct node *f, *s ; }
f = s = NULL ;

append ( &f, 1 ) ;
append ( &f, 2 ) ;
append ( &f, 3 ) ;

int compare ( struct node *q, struct node *r )


{
if ( ( q == NULL ) && ( r == NULL ) )
return SAME ;
else
{
if ( q == NULL || r == NULL )
return DIFF ; q r
if ( q -> data != r -> data )
return DIFF ; 41 2 N 41 N
else
i = compare ( q -> link, r -> link ) ;
return i ;
}
q q q r r r
}

41 2 N 41 2 N

Recursive copy( )
#include "alloc.h" append ( &f, 51 ) ;
struct node append ( &f, 29 ) ;
{ append ( &f, 7 ) ;
int data ; display ( f ) ;
struct node *link ; copy ( f, &s ) ;
};
display ( s ) ;
main( )
deleteall ( &f ) ;
{
deleteall ( &s ) ;
struct node *f, *s ;
}
f = s = NULL ;

append ( &f, 17 ) ;
append ( &f, 42 ) ;
append ( &f, 3 ) ;
append ( &f, 64 ) ;

Data Structures Through C / Lecture 28 2


copy ( struct node *q, struct node **s )
{
if ( q != NULL )
{
*s = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
( *s ) -> data = q -> data ;
( *s ) -> link = NULL ;
copy ( q -> link, &( ( *s ) -> link ) ) ;
}
} q q q q=N

12 17 24 N

12 N 17 N 24 N

*s *s *s *s

Recursive append( )
#include "alloc.h"
append ( &f, 51 ) ;
struct node append ( &f, 29 ) ;
{ append ( &f, 7 ) ;
int data ;
struct node *link ;
}; display ( p ) ;
deleteall ( &p ) ;
main( ) }
{
struct node *p ;
p = NULL ;
append ( &f, 17 ) ;
append ( &f, 42 ) ;
append ( &f, 3 ) ;
append ( &f, 64 ) ;

Empty List
*s
append ( struct node **s, int n )
{
if ( *s == NULL ) 24 N
{
*s = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
( *s ) -> data = n ;
( *s ) -> link = NULL ;
}
else
append ( &( ( *s ) -> link ), n ) ;
} Non-Empty List

*s *s

24 N 17 N

Data Structures Through C / Lecture 28 3


Linked List Using
Unions
Yashavant Kanetkar

Objectives

What are unions


Declaring and using unions
What are generalized linked lists

Problem
x7 + 2 x6 + 4 x4 + 5 x2

1 7 2 6 4 4 5 2 N

x10 y3 z2 + 2x8 y3 z2 + 3x8y2 z2 + x4 y4z + 6x3 y4z + 2yz

Solution I

1 10 3 2 2 8 3 2 3 8 2 2

1 4 4 1 6 3 4 1 2 0 1 1 N

Each node
contains a term

Data Structures Through C / Lecture 29 1


Unions z.i
00000000 00000010
Permits access to
main( ) same memory z.ch[0] z.ch[1]
{ Low High
union a locations in more
{ than one way
int i ; Binary of 512
char ch[ 2 ] ; 00000010 00000000
};
union a z ;
High Low
z.i = 512 ;
printf ( ”%d”, sizeof ( z ) ) ;
printf ( ”%d %d %d”, z.i, z.ch[ 0 ], z.ch[ 1 ] ) ;
}

Solution II - Generalized List


x10 y3 z2 + 2x8 y3 z2 + 3x8y2 z2 + x4 y4z + 6x3 y4z + 2yz
( ( x10 + 2x8 ) y3 + 3x8y2 ) z2 + ( ( x4 + 6x3 ) y4 + 2y ) z

z 0 2 1 N
var exp link pd exp link
y 0 3 2 N
struct glist
{ x 0 3 8 N
int flag ;
union varcoeffpd
x 0 1 10 2 8 N
{
char var ;
int coeff ; coeff exp link
struct glist *pd ;
} vcp ; y 0 4 2 1 N
int exp ;
struct glist *link ;
}; x 0 1 4 6 3 N

Exercise - I
2a4b6c3 + 5b3c3 + 9a2b2c - 3ab 2c + abc
( 2a4b6 + 5b3 ) c3 + ( ( 9a2 - 3a ) b2 + ( a ) b ) c

Data Structures Through C / Lecture 29 2


Exercise - II
3p7q9r5 + 7p5q9r5 - p5q8r5 + 5p 2q2r2 + 2pq2r2 - 2qr
( ( 3p7 + 7p5 ) q9 + ( - p5 ) q8 ) r5 + ( ( 5p2 + 2p ) q2 ) r2 + ( - 2q ) r

Data Structures Through C / Lecture 29 3


Generalized
Linked List
Yashavant Kanetkar

Objectives

Copying and comparing generalized linked lists

p p p p=N
Copy
a 0 5 3 1 N
# define VAR 0
# define COF 1
# define PDL 2 p b 0 2 9 1 8 N
copy ( struct glist *p, struct glist **q )
{ *q *q *q *q *q
if ( p == NULL )
*q = NULL ; a 0 5 3 1 N
else
{ b 0 2 9 1 8 N
*q = ( struct glist * ) malloc ( sizeof ( struct glist ) ) ;
**q = *p ;
if ( ( *q ) -> flag == PDL )
copy ( p -> vcp.pd, &( ( *q ) -> vcp.pd ) ) ;
copy ( p -> link, &( ( *q ) -> link ) ) ;
}
}

Data Structures Through C / Lecture 30 1


# define VAR 0 p p Depth
# define COF 1
# define PDL 2 r 0 5 1 N
depth ( struct glist *p )
{ q 0 2 N
int m = 0, n ;
if ( p == NULL ) p 0 5
return m ;
while ( p != NULL ) p q 0 -2 1 N
{
if ( p -> flag == PDL )
{
n = depth ( p -> vcp.pd ) ;
if ( n > m )
m=n;
}
p = p -> link ;
}
return ( m + 1 ) ;
}

Compare
# define DIFF 0
# define SAME 1
int compare ( struct glist *p, struct glist *q )
{
if ( ( p == NULL ) && ( q == NULL ) )
return SAME ;
p a 0 5 3 1 N

if ( p == NULL || q == NULL ) b 0 2 9 1 8
return DIFF ;
if ( p -> exp != q -> exp )
return DIFF ;
q a 0 5 3 1 N

if ( p -> flag != q -> flag )


b 0 2 9 1 8
return DIFF ;

...Contd # define VAR 0


switch ( p -> flag ) # define COF 1
{
# define PDL 2
case VAR :
if ( p -> var != q -> var )
return DIFF ;
break ;

case COF :
if ( p -> coeff != q -> coeff )
return DIFF ;
break ;

case PDL :
int i i = compare ( p -> vcp.pd, q -> vcp.pd ) ;

if ( i == DIFF )
return DIFF ;
} Contd...

Data Structures Through C / Lecture 30 2


...Contd
i = compare ( p -> link, q -> link ) ;
return i ;
}
p

a 0 5 3 1 N

b 0 2 9 1 8 N

a 0 5 2 1 N

b 0 2 9 1 8 N

Data Structures Through C / Lecture 30 3


Stack
Yashavant Kanetkar

Objectives
Stack and its utilities
Stack as an Array

Stack

Top 20
Top 10 10
Top
Empty Push 10 Push 20

Top 20
10 Top 10
Top
Pop Pop Empty

Data Structures Through C / Lecture 31 1


Utility
Store local variables in a function
Manage function calls
Conversion of Expressions
Evaluation of Expressions
Caching
push 510 display( )
{
main( ) // code
{ }
505 display( ) ; pop 510
515
510 510 show( ) ; show( )
push 515
515 puts( ) ; {
} // code
pop 515 }

#define NULL 0
#define MAX 10
Program
struct stack c = count ( s ) ;
{ printf ( "Count = %d", c ) ;
int arr[ MAX ] ; displaystack ( s ) ;
int top ; }
};
main( )
{
struct stack s ; int i, c ;
s.top = -1 ;
push ( &s, 11 ) ; top 7
push ( &s, 23 ) ; top 16
push ( &s, - 8 ) ; top -8
push ( &s, 16 ) ;
top 23
push ( &s, 7 ) ;
top 11
i = pop ( &s ) ;
top = -1
printf ( "%d", i ) ;

Push Operation
push ( struct stack *p, int item ) top 21
{
4
if ( p -> top == MAX - 1 )
{ 9
printf ( "Stack is full." ) ; 13
return ; 2
} 7
p -> top + + ; 16
p -> arr[ p ->top ] = item ; -8
} 23
top 11
top = -1

Data Structures Through C / Lecture 31 2


Pop Operation
pop ( struct stack *p )
{
int data ;
if ( p -> top == -1 )
{
printf ( "Stack is empty." ) ;
return NULL ;
top 7
}
top 16
data = p -> arr[ p -> top ] ;
p -> top - - ; -8
return data ; 23
} 11
top = -1

Display And Count


displaystack ( struct stack q )
{
int i ;
for ( i = 0 ; i <= q.top ; i + + )
printf ( "%d\t", q.arr[ i ] ) ;
}
top 7
int count ( struct stack q ) 16
{ -8
int i = 0 ; 23
while ( i <= q.top ) 11
i++;
return i ;
}

Data Structures Through C / Lecture 31 3


Stack As A
Linked List
Yashavant Kanetkar

Objectives
Stack as a Linked List

Stack As A Linked List


node data link

Push Pop

top 55 top 55

top 63 top 63

top 28 top 28

top 45 N top 45 N

Data Structures Through C / Lecture 32 1


Program
#include "alloc.h" displaystack ( top ) ;
struct node t = count ( top ) ;
{ printf ( "Total items = %d" , t ) ;
int data ;
struct node *link ; printf ( "\nPopped : " ) ;
}; item = pop ( &top ) ;
printf ( "%d ", item ) ;
main( )
displaystack ( top ) ;
{
t = count ( top ) ;
struct node *top ;
printf ( "Total items = %d" , t ) ;
int i, item ;
}
top = NULL ;
push ( &top, 45 ) ;
push ( &top, 28 ) ;
push ( &top, 63 ) ;
push ( &top, 55 ) ;

Push Operation
int push ( struct node **s, int item )
{
struct node *q ;
q = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
q -> data = item ;
q -> link = *s ; Stack
*s = q ;
} *s top
q 28

*s top
45 N
q

Pop Operation
int pop ( struct node **s ) Pop
{
struct node *q ; int item ; *s
63 top
q
if ( *s == NULL )
{
printf ( "Stack is empty" ) ; 28
return NULL ;
}
45 N
q = *s ;
item = q -> data ; *s = N top = N
*s = q -> link ;
free ( q ) ;
return ( item ) ;
}

Data Structures Through C / Lecture 32 2


Display And Count
void displaystack ( struct node *q )
{
while ( q != NULL )
{
printf ( "%2d ", q -> data ) ;
q = q -> link ;
}
}
int count ( struct node *q )
{
int c = 0 ;
while ( q != NULL )
{
q = q -> link ;
c++ ;
}
return c ;
}

Data Structures Through C / Lecture 32 3


Stack Expressions
Yashavant Kanetkar

Objectives
Expressions of different forms

Expressions

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

AB$C*D-EF/GH+/+ Postfix

+-*$ABCD//EF+GH Prefix

Data Structures Through C / Lecture 33 1


Scan from L to R. Repeat step 1- 4 In To Post
Token Operation
operand Add to expression
( Push to stack
operator Pop oper. If P(Popped) >= P(Scanned) add to expr.
Push scanned operator to stack
) Pop till ( . Add popped token to expr. Delete )
Pop stack elements if any and add to expression
A+(B* C-(D/E$F)*G )*H
Tok. Stack Expression Tok. Stack Expression
A Empty A - +(- ABC*
+ + A ( +(-( ABC*
( +( A D +(-( ABC*D
B +( AB / +(-(/ ABC*D
* +(* AB E +(-(/ ABC*DE
C +(* ABC $ +(-(/$ ABC*DE

...Contd.

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

Tok. Stack Expression


$ +(-(/$ ABC*DE
F +(-(/$ ABC*DEF
) +(- ABC*DEF$/
* +(-* ABC*DEF$/
G +(-* ABC*DEF$/G
) + ABC* D EF$/G*-
* +* ABC*DEF$/G*-
H +* ABC*DEF$/G*-H
ABC*DEF$/G*-H*+

In To Post
A$ B *C - D +E /F/ ( G+ H)

Tok. Stack Expression Tok. Stack Expression


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

Data Structures Through C / Lecture 33 2


Stack Operations
Yashavant Kanetkar

Objectives
Infix to Postfix Conversion

Program
#include "string.h" printf ( "\nEnter Infix form: " ) ;
#include "ctype.h" gets ( infix ) ;
#define MAX 50 convert ( infix, &p ) ;
struct post printf ( "Postfix expr. " ) ;
{ printf ( "%s ", p.expr ) ;
char stack[ MAX ] ; }
int top ;
char expr[ MAX ] ; Infix
}; A$ B * C- D + E /F/ ( G +H )
main( )
{ Postfix
struct post p ; AB$C*D-EF/GH+/+
char infix[ MAX ] ;
p.top = -1 ;

Data Structures Through C / Lecture 34 1


convert ( char *in, struct post *q )
{
char *pt = q -> expr ;
while ( *in != ‘\0’ )
{
if ( *in == ' ' || *in == '\t' )
in + + ;
if ( isdigit ( *in ) || isalpha ( *in ) )
{
while ( isdigit ( *in ) || isalpha ( *in ) )
{
*pt = *in ; Infix
in + + ; pt + + ; A $ B * C - D + E / F / ( G + H )
}
} Postfix
AB$C*D-EF/GH+/+

Contd...

...Contd. if ( *in == '(' )


{ Infix
push ( q, *in ) ;
in + + ; A$ B * C- D + E /F/ ( G +H )
}
F +/ AB$C*D-EF
if ( isoperator ( *in ) )
{ / +/ AB$C*D-EF/
if ( q -> top != -1 )
char opr {
opr = pop ( q ) ;
while ( priority ( opr ) >= priority ( *in ) )
{
*pt = opr ; pt + + ;
opr = pop ( q ) ;
}
push ( q, opr ) ;
}
push ( q, *in ) ;
in + + ;
} Contd...

...Contd. if ( *in == ')' )


H +/(+ AB$C*D-EF/GH
{
) +/ AB$C*D-EF/GH+
opr = pop ( q ) ;
while ( opr != '(' )
{
*pt = opr ; pt + + ;
opr = pop ( q ) ;
}
in + + ;
} ) +/ AB$C*D-EF/GH+
} // while AB$C*D-EF/GH+/+
while ( q -> top != -1 )
{
opr = pop ( q ) ;
*pt = opr ; pt + + ;
}
*pt = '\0' ;
} // convert

Data Structures Through C / Lecture 34 2


Helper Functions
priority ( char c ) isoperator ( char ch )
{ {
if ( c == '$' ) char str[ ] = "*+/%-$" ;
return 3 ; char *p ;
if ( c == '*' || c == '/' || c == '%' ) p = str ;
return 2 ; while ( *p != ‘\0’ )
if ( c == '+' || c == '-' ) {
return 1 ; if ( *p == ch )
return 0 ; return 1 ;
} p++ ;
}
return 0 ;
}

push( ) And pop( )


push ( struct post *q, char c ) char pop ( struct post *q )
{ {
if ( q -> top == MAX - 1 )
char item ;
{
printf ( "Stk. full." ) ; if ( q -> top == -1 )
return ; {
} printf ( "Stk. empty" ) ;
return -1 ;
q -> top++ ;
}
q -> stack[q -> top] = c ;
} item = q -> stack[q -> top] ;
q -> top-- ;
return item ;
}

Data Structures Through C / Lecture 34 3


Postfix
Yashavant Kanetkar

Objectives
Evaluation of Postfix form

Evaluate Postfix
Scan from L to R. Repeat step 1- 2
Token Operation
operand Add to stack
operator Pop stack into n1
Pop stack into n2
Perform n3 = n2 operator n1
Push n3
Pop stack to obtain result

Data Structures Through C / Lecture 35 1


4 2 $ 3*3 -8 4 / 1 1 + / +
Token Stack
4 4
2 4, 2
$ 16
3 16, 3
* 48
3 48, 3
- 45
8 45, 8
4 45, 8, 4
/ 45, 2
1 45, 2, 1
1 45, 2, 1, 1
+ 45, 2, 2
/ 45, 1
+ 46

Program
# include "math.h"
# include "ctype.h "
main( )
{
char expr[ MAX ] ;
int val ;

printf ( "\nEnter postfix expr.: " ) ;


gets ( expr ) ;
val = calculate ( expr ) ;
printf ( "\nValue = %d", val ) ;
}

#define MAX 50 else


{
struct postfix n1 = pop ( &pf ) ;
{ n2 = pop ( &pf ) ;
int stack[ MAX ] ; switch ( *s )
int top ; {
}; case '+' :
calculate ( char *s ) n3 = n2 + n1 ;
{ break ;
struct postfix pf ; ..
int res , n1, n2, n3 ; case '$' :
pf.top = -1 ; n3 = pow ( n2 , n1 ) ;
break ;
while ( *s != '\0' ) }
{ push ( &pf, n3 ) ;
if ( isdigit ( *s ) ) }
{ s++ ;
res = *s - '0' ; }
push ( &pf, res ) ; res = pop ( &pf ) ;
} return res ;
}

Data Structures Through C / Lecture 35 2


Infix To Prefix
Yashavant Kanetkar

Objectives
Infix to Prefix Conversion

Scan from R to L. Repeat step 1- 4 In To Pre


Token Operation
operand Add to expression
) Push to stack
operator Pop oper. If P(popped) > P(Scanned) add to expr.
Push scanned operator to stack
( Pop till ) . Add popped token to expr. Delete )
Pop stack elements if any and add to expression
A$ B * C- D + E /F/ ( G +H )
Tok. Stack Expression Tok. Stack Expression
) ) Empty F / F+GH
H ) H / // F+GH
+ )+ H E // EF+GH
G )+ GH + + //EF+GH
( Empty +GH D + D//EF+GH
/ / +GH - +- D//EF+GH

Data Structures Through C / Lecture 36 1


...Contd.

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

Tok. Stack Expression


- +- D//EF+GH
C +- CD//EF+GH
* +-* CD//EF+GH
B +-* BCD//EF+GH
$ +-*$ BCD//EF+GH
A +-*$ ABCD//EF+GH
+-*$ABCD//EF+GH

Infix To Prefix
A+(B* C-(D/E$F)*G )*H

Tok. Stack Expression Tok. Stack Expression


H Empty H D *)*)/ D$ E F G H
* * H ( *)* /D$EFGH
) *) H - *)- */D$EFGH
G *) GH C *)- C*/D$EFGH
* *)* GH * *)-* C*/D$EFGH
) *)*) GH B *)-* BC*/D$EFGH
F *)*) FGH ( * -*BC*/D$EFGH
$ *)*)$ FGH + + *-*BC*/D$EFGH
E *)*)$ EFGH A + A* - * B C * / D $ E F G H
/ *)*)/ $EFGH + A* - * B C * / D $ E F G H

convert ( char *in, struct pre *q )


{
char *pt ;
int l = strlen ( in ) ;
in = in + ( l - 1 ) ;
pt = q -> expr + ( l - 1 ) ;
*( q -> expr + l ) = '\0' ; Infix
A$ B * C- D + E /F/ ( G +H )
while ( l != 0 )
{
if ( *in == ' ' || *in == '\t' ) Prefix
{ +-*$ABCD//EF+GH
in - - ;
l--;
}
while ( isdigit ( *in ) || isalpha ( *in ) )
{
*pt = *in ;
in - - ; l - - ; pt - - ;
} Contd...

Data Structures Through C / Lecture 36 2


...Contd.
if ( *in == ')' ) Infix
{ A$ B * C- D + E /F/ ( G +H )
push ( q, *in ) ;
in - - ; l - - ;
} Prefix
if ( isoperator ( *in ) ) + - * $ A B C D / / E F + G H
{
if ( q -> top != -1 )
char opr {
opr = pop ( q ) ;
while ( priority ( opr ) > priority ( *in ) )
{
*pt = opr ; pt - - ;
opr = pop ( q ) ;
}
push ( q, opr ) ;
}
push ( q, *in ) ;
in - - ; l - - ;
} Contd...

...Contd. if ( *in == '(' ) G )+ GH


{ ( Empty +GH
opr = pop ( q ) ;
while ( opr != ')' )
{
*pt = opr ; pt - - ;
opr = pop ( q ) ;
}
in - - ; l - - ;
} A +-*$ A B C D / / E F + G H
} // while +-*$ABCD//EF+GH
while ( q -> top != -1 )
{
opr = pop ( q ) ;
*pt = opr ; pt - - ;
}
pt + + ;
strcpy ( q -> expr, pt ) ;
}

Data Structures Through C / Lecture 36 3


Postfix To Prefix
Yashavant Kanetkar

Objectives
Evaluation of Prefix form
Postfix to Prefix Conversion

Evaluate Prefix
Scan from R to L. Repeat step 1- 2
Token Operation
operand Add to stack
operator Pop stack into n1
Pop stack into n2
Perform n3 = n1 operator n2
Push n3
Pop stack to obtain result

Data Structures Through C / Lecture 37 1


+ - * $ 4 2 3 3 / / 8 4 + 1 1
Token Stack
1 1
1 1, 1
+ 2
4 2, 4
8 2, 4, 8
/ 2, 2
/ 1
3 1, 3
3 1, 3, 3
2 1, 3, 3, 2
4 1, 3, 3, 2, 4
$ 1, 3, 3, 16
* 1, 3, 48
- 1, 45
+ 46

Scan from L to R. Repeat step 1- 2 Post To Pre


Token Operation
operand Push to stack
operator Pop stack into s1
Pop stack into s2
Concatenate operator s2 s1
Push result on stack
Pop stack to obtain result
AB$C*D-EF/GH+/+
Tok. Stack Tok. Stack
A A - -*$ABCD
B AB E - * $ A B C D, E
$ $AB F - * $ A B C D, E, F
C $ A B, C / - * $ A B C D, / E F
* *$ABC G - * $ A B C D, / E F, G
D * $ A B C, D H - * $ A B C D, / E F, G, H

...Contd.

AB$C*D-EF/GH+/+

Tok. Stack
H - * $ A B C D, / E F, G, H
+ - * $ A B C D, / E F, + G H
/ - * $ A B C D, / / E F + G H
+ +-*$ABCD//EF+GH

Data Structures Through C / Lecture 37 2


Post To Pre
ABC*DEF$/G*-H*+
Tok. Stack
A A
B A, B
C A, B, C
* A, * B C
D A, * B C, D
E A, * B C, D, E
F A, * B C, D, E, F
$ A, * B C, D, $ E F
/ A, * B C, / D $ E F
G A, * B C, / D $ E F, G
* A, * B C, * / D $ E F G
- A, - * B C * / D $ E F G
H A, - * B C * / D $ E F G, H
* A, * - * B C * / D $ E F G H
+ +A*-*BC*/D$EFGH

#include "string.h"
#define MAX 50
Program
struct postfix Postfix
{ AB$C*D-EF/GH+/+
char stack[ MAX ][ MAX ] ;
int top ; Prefix
}; +-*$ABCD//EF+GH
main( )
{
struct postfix q ;
char expr[ MAX ] ;
q.top = -1 ;
printf ( "Enter postfix expr: " ) ;
gets ( expr ) ;
convert ( expr, &q ) ;
printf ( "\nPrefix expr: " ) ;
printf ( "%s", &q.stack[ 0 ][ 0 ] ) ;
}

convert ( char *str, struct postfix *p )


{
char temp[ MAX ] ;
char *s1, *s2 ;
while ( *str != '\0' )
{
temp[ 0 ] = *str ; temp[ 1 ] = '\0' ;
if ( isoperator ( *str ) )
{
s1 = pop ( p ) ; A B $ C * D
s2 = pop ( p ) ;
strcat ( temp, s2 ) ;
strcat ( temp, s1 ) ;
}
push ( p, temp ) ;
str + + ; Top C
D
B
}
Top
Top A
$* A
$ A
B B C
}

Data Structures Through C / Lecture 37 3


push( )
push ( struct postfix *p, char *str )
{
if ( p -> top == MAX - 1 )
{
printf ( "\nStack is full." ) ;
return ;
}
p -> top + + ;
strcpy ( p -> stack[ p -> top ], str ) ;
}

pop( )
char * pop ( struct postfix *p )
{
char *pstr ;
if ( p -> top == -1 )
{
printf ( "\nStack is empty." ) ;
return 0 ;
}
pstr = p -> stack[ p -> top ] ;
p -> top - - ;
return pstr ;
}

Data Structures Through C / Lecture 37 4


More Conversion
Yashavant Kanetkar

Objectives
Prefix to Postfix Conversion
Prefix to Infix Conversion

Scan from R to L. Repeat step 1- 2 Pre To Post


Token Operation
operand Push to stack
operator Pop stack into s1
Pop stack into s2
Concatenate s1 s2 operator
Push result on stack
Pop stack to obtain result
+-*$ABCD//EF+GH
Tok. Stack Tok. Stack
H H / EF/GH+/
G H, G D E F / G H + /, D
+ GH+ C E F / G H + /, D, C
F G H +, F B E F / G H + /, D, C, B
E G H +, F, E A E F / G H + /, D, C, B, A
/ G H +, E F / $ E F / G H + /, D, C, A B $

Data Structures Through C / Lecture 39 1


...Contd.

+-*$ABCD//EF+GH

Tok. Stack
$ E F / G H + /, D, C, A B $
* E F / G H + /, D, A B $ C *
- E F / G H + /, A B $ C * D -
+ AB$C*D-EF/GH+/+

Pre To Post
+A*-*BC*/D$EFGH
Tok. Stack
H H
G H, G
F H, G, F
E H, G, F, E
$ H, G, E F $
D H, G, E F $, D
/ H, G, D E F $ /
* H, D E F $ / G *
C H, D E F $ / G * , C
B H, D E F $ / G * , C, B
* H, D E F $ / G * , B C *
- H, B C * D E F $ / G * -
* BC*DEF$ /G*-H*
A BC*DEF$ /G*-H*,A
+ ABC*DEF$/G*-H*+

convert ( char *str, struct postfix *p )


{
char temp[ MAX ] ;
int l ; char *s1, *s2 ; * E F / G H + /, D, A B $ C *
l = strlen ( str ) ; - E F / G H + /, A B $ C * D -
str = str + ( l - 1 ) ;
while ( l != 0 )
{
temp[ 0 ] = *str ; temp[ 1 ] = '\0' ;
if ( isoperator ( *str ) )
{
s1 = pop ( p ) ; s2 = pop ( p ) ;
strcat ( s1, s2 ) ; strcat ( s1, temp ) ;
strcpy ( temp, s1 ) ; Prefix
}
push ( p, temp ) ; +-*$ABCD//EF+GH
str - - ; l - - ; Postfix
}
} AB$C*D-EF/GH+/+

Data Structures Through C / Lecture 39 2


Scan from R to L. Repeat step 1- 2 Pre To In
Token Operation
operand Push to stack
operator Pop stack into s1
Pop stack into s2
Concatenate s1 operator s2
Push result on stack
Pop stack to obtain result
+-*$ABCD//EF+GH
Tok. Stack Tok. Stack
H H / E/F/G+H
G HG D E / F / G + H, D
+ G+H C E / F / G + H, D, C
F G + H, F B E / F / G + H, D, C, B
E G + H, F, E A E / F / G + H, D, C, B, A
/ G + H, E / F $ E / F / G + H, D, C, A $ B

...Contd.

+-*$ABCD//EF+GH

Tok. Stack
$ E / F / G + H, D, C, A $ B
* E / F / G + H, D, A $ B * C
- E / F / G + H, A $ B * C - D
+ A$B*C-D+E/F/G+H

Pre To In
+A*-*BC*/D$EFGH
Tok. Stack
H H
G H, G
F H, G, F
E H, G, F, E
$ H, G, E $ F
D H, G, E $ F, D
/ H, G, D / E $ F
* H, D / E $ F * G
C H, D / E $ F * G, C
B H, D / E $ F * G, C, B
* H, D / E $ F * G, B * C
- H, B * C - D / E $ F * G
* B*C-D/E$ F* G* H
A B * C - D / E $ F * G * H, A
+ A+ B*C-D/E$ F* G* H

Data Structures Through C / Lecture 39 3


convert ( char *str, struct infix *p )
{
char temp[ MAX ] ;
int l ; char *s1, *s2 ; * E / F / G + H, D, A $ B * C
l = strlen ( str ) ; - E / F / G + H, A $ B * C - D
str = str + ( l - 1 ) ;
while ( l != 0 )
{
temp[ 0 ] = *str ; temp[ 1 ] = '\0' ;
if ( isoperator ( *str ) )
{
s1 = pop ( p ) ; s2 = pop ( p ) ;
strcat ( s1, temp ) ; strcat ( s1, s2 ) ;
strcpy ( temp, s1 ) ; Prefix
}
push ( p, temp ) ; +-*$ABCD//EF+GH
str - - ; l - - ; Infix
}
} A$ B * C- D + E /F/ G +H

Summary
Conversion Scan Order Token Operation
In - Post L-R operand Add to expression
operator Priority
In - Pre R-L ( Add to stack / delete
) Add to stack / delete
Post - Pre L-R operand Push to stack
Post - In L-R operator Pop stack into s1
Pop stack into s2
Pre - Post R-L
Construct expression
Pre - In R-L Push expression on stack

In Post s1 B Pre s1 A
A$B AB$ s2 A $AB s2 B

Data Structures Through C / Lecture 39 4


Queue - I
Yashavant Kanetkar

Objectives
Queue

Queue

WM_PAINT WM_KEYDOWN

WM_CREATE WM_MOUSEMOVE

Message queue

Retrieved Messages

WinMain( ) Message loop

Dispatched Messages
Call Appropriate Handler

Data Structures Through C / Lecture 40 1


Queue
front rear

16 - 8 23 11 7

front rear rear Addition

16 - 8 23 11 7 13

front front rear Deletion

16 - 8 23 11 7 13

Program
#define MAX 10
#define NULL 0 i = delq ( &q ) ;
printf ( "\nItem = %d", i ) ;
struct queue
{ }
int arr[ MAX ] ;
int f, r ;
};
main( )
{
struct queue q ; int i ;
q.f = q.r = -1 ;
addq ( &q, 23 ) ;
addq ( &q, 9 ) ;
addq ( &q, 11 ) ;
addq ( &q, -10 ) ;

addq( )
addq ( struct queue *p, int item )
{
if ( p -> r == MAX - 1 )
{
printf ( "\nQueue is full." ) ;
return ;
}
p -> r++ ;
p -> arr[ p -> r ] = item ;
if ( p -> f == -1 ) f = -1
p -> f = 0 ; r = -1
} 23

f r

23 9 11 -10 7 13 2 - 8 22 3

Data Structures Through C / Lecture 40 2


delq( )
delq ( struct queue *p ) data = p -> arr[ p -> f ] ;
{ if ( p -> f == p -> r )
int data ; p -> f = p -> r = -1 ;
if ( p -> f == -1 ) else
{ p -> f++ ;
printf ( "\nEmpty." ) ; return data ;
return NULL ;
}
}
f

23 9 11 -10 7

f r f = -1
r = -1
23 9 11 -10 7

Data Structures Through C / Lecture 40 3


Queue - II
Yashavant Kanetkar

Objectives
Limitations of Queue
Circular Queues

Problems
f r

5 -1 34 12 53 61 9 23 - 8 42

Solution I Shift elements


f r

-1 34 12 53 61 9 23 - 8 42 42

Solution II Circular Queue


r f rr

7 -1 34 12 53 61 9 23 - 8 42

Data Structures Through C / Lecture 41 1


Program
#define MAX 10 addq ( &q, 5 ) ;
struct queue addq ( &q, - 1 ) ;
{ addq ( &q, 34 ) ;
int arr[ MAX ] ; addq ( &q, 12 ) ;
int f, r ; addq ( &q, 53 ) ;
};
printf ( "\nCircular queue: " ) ;
main( ) for ( i = 0 ; i < MAX ; i + + )
{ printf ( "%d\t", q.arr[ i ] ) ;
struct queue q ;
int i ; i = delq ( &q ) ;
printf ( "Item = %d", i ) ;
q.f = q.r = -1 ;
for ( i = 0 ; i < MAX ; i + + ) printf ( "\nCircular queue: " ) ;
q.arr[ i ] = 0 ; for ( i = 0 ; i < MAX ; i + + )
printf ( "%d\t", q.arr[ i ] ) ;
}

addq( )
addq ( struct queue *p, int item )
{
if ( ( p -> r == MAX - 1 && p -> f == 0 ) ||
( p -> r + 1 == p -> f ) )
{
printf ( "\nQueue is full." ) ; f = -1
return ; r = -1
} -8
if ( p -> r == MAX - 1 )
p -> r = 0 ; f r
else
p -> r + + ; 9 42 34 12 53
p -> arr[ p -> r ] = item ;
f r
if ( p -> f == -1 )
p -> f = 0 ;
- 8 42 34 12 53
}

delq ( struct queue *p )


{
delq( )
int i ;
if ( p -> f == -1 ) f = -1
{ r = -1
printf ( "\nQueue is empty." ) ;
return 0 ;
}
i = p -> arr[ p -> f ] ; p -> arr[ p -> f ] = 0 ;
if ( p -> f == p -> r ) f r
p -> r = p -> f = -1 ;
else
-08 42 34 12 53
{
if ( p -> f == MAX - 1 )
p -> f = 0 ;
else f r
p -> f + + ;
}
return i ; 9 42 0 0 53
0
}

Data Structures Through C / Lecture 41 2


Deque &
Priority Queue
Yashavant Kanetkar

Objectives
Deque
Priority Queue

Deque
f r

5 -1 34 12 53 61 9 23 - 8 42

f r

5 -1 34 12 53 61 9 23 - 8 42

f r

5 -1 34 12 53 61 9 23 - 8 42

Data Structures Through C / Lecture 42 1


Program
#define MAX 10 printf ( "\nDeque: " ) ;
struct deque for ( i = 0 ; i < MAX ; i + + )
{ printf ( "\t%d", dq.arr[ i ] ) ;
int arr[ MAX ] ;
int f, r ; i = delqatbeg ( &dq ) ;
}; printf ( "\nItem = %d", i ) ;
main( ) printf ( "\nDeque: " ) ;
{ for ( i = 0 ; i < MAX ; i + + )
struct deque q ; int i ;
printf ( "\t%d", dq.arr[ i ] ) ;
dq.f = dq.r = -1 ;
for ( i = 0 ; i < MAX ; i + + ) i = delqatend ( &dq ) ;
dq.arr[ i ] = 0 ; printf ( "\nItem = %d", i ) ;
addqatend ( &dq, 17 ) ;
printf ( "\nDeque: " ) ;
addqatbeg ( &dq, 10 ) ;
for ( i = 0 ; i < MAX ; i + + )
addqatend ( &dq, 8 ) ;
printf ( "\t%d", dq.arr[ i ] ) ;
addqatbeg ( &dq, -9 ) ;
}
addqatend ( &dq, 13 ) ;

addqatend ( struct deque *p, else


int item ) p -> r + + ;
{ p -> arr[ p->r ] = item ;
int i ;
}
if ( p -> f == 0 && p -> r == MAX-1 )
{
printf ( "Deque is full." ) ; f r
return ;
}
if ( p -> f == -1 ) 0 42 34 12 9
{
p -> r = p -> f = 0 ; f r
p -> arr[ p -> r ] = item ;
return ; 42 34 12 9 -98
}
if ( p -> r == MAX - 1 )
{
for ( i = p -> f-1 ; i < p -> r ; i + + )
p -> arr[ i ] = p -> arr[ i + 1 ] ;
p -> f - - ;
}

addqatbeg ( struct deque *p, else


int item ) p -> f - - ;
{ p -> arr[ p->f ] = item ;
int i ; }
if ( p -> f == 0 && p -> r == MAX-1 )
{
printf ( "Deque is full." ) ;
return ; f r
}
if ( p -> f == -1 ) - 8 42 34 12 53
{
p -> f = p -> r = 0 ;
p -> arr[ p -> f ] = item ; f r f = -1
return ; r = -1
} 17
if ( p -> f == 0 )
{ f r
for ( i = p -> r+1 ; i > p -> f ; i- - )
p -> arr[ i ] = p -> arr[ i - 1 ] ;
p -> r + + ; 17
9 42 9 34 42 3412 12 0
}

Data Structures Through C / Lecture 42 2


delqatbeg ( struct deque *p )
{
int item ;
if ( p -> f == -1 )
{
printf ( "Deque is empty." ) ;
return 0 ;
} f r
item = p -> arr[ p -> f ] ;
p -> arr[ p -> f ] = 0 ; - 08 42 34 12 53
if ( p -> f == p -> r )
p -> f = p -> r = -1 ; f r
else
p -> f + + ;
0 42 0 0 0
return item ;
}

delqatend ( struct deque *p )


{
int item ;
if ( p -> f == -1 )
{
printf ( "Deque is empty." ) ;
return 0 ;
} f r
item = p -> arr[ p -> r ] ;
p -> arr[ p -> r ] = 0 ; - 8 42 34 12 53
0
p -> r - - ;
if ( p -> r == -1 ) f r
p -> f = -1 ;
return item ; 42 0 0 0 0
}

Priority Queue
Job Priority f r f r f r
2 2
9 4 2 9 2 9 2 8
8 2
3 3
f r
6 1
1 4
7 5 9 3 2 8
4 4
0 4 f r
5 2
9 3 2 8 6

Data Structures Through C / Lecture 42 3


Trees
Yashavant Kanetkar

Objectives
Trees
Trees terminology
Types of Trees

Data structures
Linear Non - Linear

Arrays Trees
Linked Lists Graphs
Stacks
Queues

Data Structures Through C / Lecture 43 1


Trees
RAHUL

SANJAY SAMEER NISHA


N N N N N

ABHA AJIT MADHU NEHA


N N N N N N N N N N N N

General Trees And Forest

A T1 T2 T3
A @ 99
ST1 ST2
K Z
D $ & 45 55
D S G C ^ 35
G M N H
C
H O P ~ 0 25
H #
15

Terminology Binary Tree - Each node


has 0, 1, 2 children

A A - Root node
B, D, F - Nodes of left sub-tree
B C C, E, G, H - Nodes of right sub-tree
F, G, H - Leaf nodes
D E
A is Father of B & C
F G H E is right child C
G is right descendant of A
F is left child of D
F is left descendant of A
A is ancestor of D
G & H are siblings, D and E aren’t

Data Structures Through C / Lecture 43 2


More Terminology
A

B C

D E

F G H

Degree of a node is no. of nodes connected to it

Level of root node is 0


Level of any other node is 1 more than level of its father

Depth of a binary tree is maximum level of a node

Strictly And Complete


A A

B C B C

D E D E F G

F G

Strictly Binary Tree Complete Binary Tree


Each non-leaf node has 2 Strictly binary tree with all
children leaf nodes at same level

Data Structures Through C / Lecture 43 3


Tree Traversal
Yashavant Kanetkar

Objectives
Traversal of Trees
Reconstruction of Trees

Traversal
A

B C

D E

F G

Pre-order Traversal - Root - Left - Right A, B, D, E, F, G, C


In-order Traversal - Left - Root - Right D, B, F, E, G, A, C
Post-order Traversal - Left - Right - Root D, F, G, E, B, C, A

Data Structures Through C / Lecture 44 1


Exercise
3

2 7

8 9

4 1 6

Pre-order Traversal - Root - Left - Right 3, 2, 8, 4, 7, 9, 1, 6


In-order Traversal - Left - Root - Right 2, 4, 8, 3, 7, 1, 9, 6
Post-order Traversal - Left - Right - Root 4, 8, 2, 1, 6, 9, 7, 3

Reconstruction - I In - 4, 7, 2, 8, 5, 1, 6, 9, 3
Pre - 1, 2, 4, 7, 5, 8, 3, 6, 9
1
1

In: 4, 7, 2, 8, 5 In: 6, 9, 3 2 In: 6, 9, 3


Pre: 2, 4, 7, 5, 8 Pre: 3, 6, 9 Pre: 3, 6, 9

1 In: 4, 7 In: 8, 5 1
Pre: 4, 7 Pre: 5, 8

2 3 2 3

4 5 In: 6, 9 4 5 6
Pre: 6, 9

7 8 7 8 9

Exercise In - 2, 4, 8, 3, 7, 1, 9, 6
Pre - 3, 2, 8, 4, 7, 9, 1, 6
3
3

In: 2, 4, 8 In: 7, 1, 9, 6 In: 7, 1, 9, 6


2
Pre: 2, 8, 4 Pre: 7, 9, 1, 6 Pre: 7, 9, 1, 6

In: 4, 8
3 Pre: 8, 4 3

2 7 2 7

8 In: 1, 9, 6 8 9
Pre: 9, 1, 6
4 4 1 6

Data Structures Through C / Lecture 44 2


Reconstruction - II In - 5, 7, 20, 15, 9, 8, 4
Post - 5, 7, 9, 4, 8, 15, 20
20
20

In: 5, 7 In: 15, 9, 8, 4 In: 15, 9, 8, 4


Post: 5, 7 7
Post: 9, 4, 8, 15 Post: 9, 4, 8, 15
5 20
20
7 15
7 15
5 8
5 In: 9, 8, 4
Post: 9, 4, 8 9 4

Exercise In - D, B, F, E, G, A, C
Post - D, F, G, E, B, C, A
A

In: D, B, F, E, G In: C
Post: D, F, G, E, B Post: C B C

A
D In: F, E, G
Post: F, G, E
B C

D E

F G

Reconstruction - III Pre - 9, 3, 5, 1, 17, 2, 4


Post - 5, 1, 3, 4, 2, 17, 9
9
9

Pre: 3, 5, 1 Pre: 17, 2, 4 3 Pre: 17, 2, 4


Post: 5, 1, 3 Post: 4, 2, 17 Post: 4, 2, 17

5 1 9
9
17
3
3 17
2
Pre: 2, 4 5 1
5 1 Post: 4, 2
4

Data Structures Through C / Lecture 44 3


Exercise Pre - 16, 8, 2, 13, 10, 24, 19, 25
Post - 2, 10, 13, 8, 19, 25, 24, 16
16

Pre: 8, 2, 13,10 Pre: 24, 19, 22 16


Post: 2, 10, 13, 8 Post: 19, 25, 24
8 Pre: 24, 19, 25
16 Post: 19, 25, 24

8 2 2 Pre: 13, 10
Post: 10, 13

2 13 19 25

10

Data Structures Through C / Lecture 44 4


BST - I
Yashavant Kanetkar

Objectives
How to represent trees using arrays and linked
lists
What are binary search trees

Array Representation
3 - Arrays
0 1 2 3 4 5 6 7 8 9
A arr A B C D E F G '\0' '\0' H
lc 1 3 5 -1 9 -1 -1 -1 -1 -1
B C
rc 2 4 6 -1 -1 -1 -1 -1 -1 -1

E 1 - Array 2 ( depth + 2 ) - 1
D F G
0 1 2 3 4 5 6 7 8 9
arr A B C D E F G '\0' '\0' H
H 10 11 12 13 14 15 16 17 18 19
'\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0'
lc = 2 pos + 1
20 21 22 23 24 25 26 27 28 29 30
rc = 2 pos + 2
'\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0'

Data Structures Through C / Lecture 45 1


Exercise
0 1 2 3 4 5 6 7 8 9 10 11 12
arr 3 2 7 -1 8 -1 9 -1 -1 4 -1 1 6
lc 1 - 1 - 1 - 1 9 - 1 11 - 1 - 1 - 1 - 1 - 1 - 1

3 rc 2 4 6 - 1 - 1 - 1 12 - 1 - 1 - 1 - 1 - 1 - 1

2 7

8 9

4 1 6

Linked Representation
A

B C

N D N E N N F N N G N

N H N struct btnode
{
struct btnode *lc ;
char data ;
struct btnode *rc ;
};

Binary Search Tree


10 10, 6, 8, 15, 20, 7, 13, 5

Greater goes to right


6 15
Smaller goes to left
In-order gives ascending order
5 8 13 20 5, 6, 7, 8, 10, 13, 15, 20

Data Structures Through C / Lecture 45 2


Exercise

L Y

A U W Z

D X

Data Structures Through C / Lecture 45 3


BST - II
Yashavant Kanetkar

Objectives
A program to traverse the trees
Traversal of trees using inorder, preorder and
postorder
Non recursive traversal of trees
Comparing two trees

Program
# include "alloc.h" printf ( "\nIn-order: " ) ;
struct btnode inorder ( bt ) ;
{
struct btnode *lc ; printf ( "\nPre-order: " ) ;
int data ; preorder ( bt ) ;
struct btnode *rc ;
}; printf ( "\nPost-order: " ) ;
main( ) postorder ( bt ) ;
{
struct btnode *bt ; deleteall ( bt ) ;
}
bt = NULL ;
insert ( &bt, 10 ) ;
insert ( &bt, 6);
insert ( &bt, 8);
insert ( &bt, 15 ) ;
insert ( &bt, 20 ) ;

Data Structures Through C / Lecture 46 1


insert ( struct btnode **p, int num ) Empty
{ *p
if ( *p == NULL )
{ N 10 N
*p = ( struct btnode * ) malloc (
sizeof ( struct btnode ) ) ; Non-empty
( *p ) -> lc = NULL ; *p
( *p ) -> data = num ;
( *p ) -> rc = NULL ; N 10 N
}
*p N 6 N 15 N
else
{ *p N 8 N *p
if ( num < ( *p ) -> data )
insert ( &( ( *p ) -> lc ), num ) ;
else
insert ( &( ( *p ) -> rc ), num ) ;
}
}

inorder ( struct btnode *p )


{
if ( p != NULL )
{
inorder ( p -> lc ) ;
printf ( "\t %d", p -> data ) ;
inorder ( p -> rc ) ; p
}
} p 10
preorder ( struct btnode *p )
{ N 6 N 15 N
if ( p != NULL ) p N 8 N p
{
printf ( "\t %d", p -> data ) ;
preorder ( p -> lc ) ;
preorder ( p -> rc ) ;
}
}

postorder ( struct btnode *p )


{
if ( p != NULL )
{
postorder ( p -> lc ) ;
postorder ( p -> rc ) ;
printf ( "\t%d", p -> data ) ;
} p
}
deleteall ( struct btnode *p ) p 10
{
if ( p != NULL ) N 6 N 15 N
{ p
p N 8 N
deleteall ( p -> lc ) ;
deleteall ( p -> rc ) ;
free ( p ) ;
}
}

Data Structures Through C / Lecture 46 2


Compare Trees
#include "alloc.h " insert ( &bt1, 3 ) ;
# define TRUE 1 insert ( &bt1, 10 ) ;
# define FALSE 0 insert ( &bt1, 4 ) ;
insert ( &bt1, 2 ) ;
struct btnode
{ insert ( &bt2, 5 ) ;
struct btnode *lc ; insert ( &bt2, 3 ) ;
int data ; insert ( &bt2, 10 ) ;
struct btnode *rc ; insert ( &bt2, 4 ) ;
}; insert ( &bt2, 2 ) ;
main( )
{ compare ( bt1, bt2, &i ) ;
struct btnode *bt1, *bt2 ; if ( i == TRUE )
int i ; printf ( "Equal" ) ;
bt1 = bt2 = NULL ; else
printf ( "Unequal" ) ;
insert ( &bt1, 5 ) ; }

compare ( struct btnode *p, struct btnode *q, int *flag )


{
*flag = FALSE ;
p 5
if ( p == NULL && q == NULL )
*flag = TRUE ;
if ( p != NULL && q != NULL ) 3 10
{
if ( p -> data != q -> data )
*flag = FALSE ; 2 4 7
else
{
compare ( p -> lc, q -> lc, flag ) ;
if ( *flag != FALSE )
compare ( p -> rc, q -> rc, flag ) ;
}
}
}

Data Structures Through C / Lecture 46 3


Binary Tree
Yashavant Kanetkar

Objectives
How to perform insertion on binary search trees
How to delete an existing node from a binary
search tree
How to search a node in a binary search tree

Successor And Predecessor


In - 5, 7, 9, 10, 11, 12, 14
11 Pre - 11, 7, 5, 10, 9, 14, 12
Post - 5, 9, 10, 7, 12, 14, 11
7 14
In - order successor of 7 is 9
In - order predecessor of 7 is 5
5 10 12
Pre - order successor of 5 is 10
Pre - order predecessor of 5 is 7
9
Post - order successor of 12 is14
Post - order predecessor of 12 is 7

In - order successor of a node with


two child is always a leaf node or a
node with only right child

Data Structures Through C / Lecture 47 1


Program
# include "alloc.h" insert ( &bt, 9 ) ;
struct btnode insert ( &bt, 12 ) ;
{ printf ( "\nBST: " ) ;
struct btnode *lc ; inorder ( bt ) ;
int data ;
struct btnode *rc ; delete ( &bt, 14 ) ;
}; delete ( &bt, 7 ) ;
main( ) delete ( &bt, 5 ) ;
{
struct btnode *bt ; printf ( "\nBST: " ) ;
bt = NULL ; inorder ( bt ) ;
insert ( &bt, 11 ) ;
deleteall ( bt ) ;
insert ( &bt, 7);
}
insert ( &bt, 10 ) ;
insert ( &bt, 14 ) ;
insert ( &bt, 5);

insert ( struct btnode **pt, int num ) Empty


{
struct btnode *t, *p, *c ; *pt t
t = ( struct btnode * ) malloc (
sizeof ( struct btnode ) ) ; N 11 N
t -> data = num ;
t -> rc = t -> lc = NULL ; Non-empty
pc c = N
if ( *pt == NULL )
*pt = t ; p
else N 11 N
{
p = c = *pt ; t N 7 N N 14 N
while ( c != NULL ) c
{ t N 10 N t
p=c;
num < p -> data ? ( c = p -> lc ) : ( c = p -> rc ) ;
}
num < p -> data ? ( p -> lc = t ) : ( p -> rc = t ) ;
}
}

delete ( struct btnode **pt, int num ) *pt


{
struct btnode *p, *c ;
int found ; 11

if ( *pt == NULL )
7 14
{
printf ( "\nTree is empty" ) ;
return ;
5 10 12
}
p = c = NULL ;
found = search ( pt, num, &p, &c ) ; 9
# define TRUE 1
if ( found == FALSE ) # define FALSE 0
{
printf ( "\nData not found" ) ;
return ;
} Contd...

Data Structures Through C / Lecture 47 2


...Contd

if ( c -> lc != NULL && c -> rc != NULL )


{
p=c; *pt
csucc = c -> rc ;
struct btnode *csucc pc 11
while ( csucc -> lc != NULL )
{ 7
9 14
p csucc
p = csucc ;
csucc = csucc -> lc ;
} 5 10 12
c
c -> data = csucc -> data ;
c = csucc ;
9 csucc
}

Contd...

...Contd 11
if ( c -> lc == NULL && c -> rc == NULL )
t = NULL ; 10 12
struct btnode *t
if ( c -> lc == NULL && c -> rc != NULL ) 9
t = c -> rc ; p
if ( c -> lc != NULL && c -> rc == NULL )
t = c -> lc ; cp 11
p
if ( p -> lc == c )
p -> lc = t ;
11 c c 7 t 14
else
p -> rc = t ;
10
free ( c ) ; t 14 5 10 12
}
9
12 9

search ( struct btnode **pt, int num, struct btnode **p,


struct btnode **pc )
{ q *pt
struct btnode *q ;
q = *pt ; *p
q *p 11
*p = NULL ;
while ( q != NULL )
{ 7 14
q
if ( q -> data == num )
{
5 10 12
*pc = q ;
return TRUE ;
} *pc
9
*p = q ;
num < q -> data ? ( q = q -> lc ) : ( q = q -> rc ) ;
}
return FALSE ;
}

Data Structures Through C / Lecture 47 3


Treaded Binary
Trees
Yashavant Kanetkar

Objectives
What are threaded binary trees
How threaded binary trees are represented
How to insert a node in a threaded binary tree
How to traverse the threaded binary tree in
inorder

Threaded Binary Tree


A. J. Perlis
C. Thornton

Links
Threads
11
struct thtree
{
8 16 struct thtree *lc ;
int haslt ;
int data ;
3 10 int hasrt ;
struct thtree *rc ;
};
6
Left - Predecessor or head
Right - Successor or head

Data Structures Through C / Lecture 48 1


Linked Representation
F - 9999 F

F 11 F

F 8 F T 16 T

T 3 F T 10 T

T 6 T

17
Exercise
In: 10, 13, 17, 20, 27, 38, 81
10 38 Post: 13, 10, 20, 27, 81, 38, 17

13 27 81

20

Program
# include "alloc.h" insert ( &th_head, 8 ) ;
# define TRUE 1 insert ( &th_head, 16 ) ;
# define FALSE 0 insert ( &th_head, 3 ) ;
struct thtree insert ( &th_head, 6 ) ;
{ insert ( &th_head, 10 ) ;
struct thtree *lc ; printf ( "Threaded BT:\n" ) ;
int haslt ; inorder ( th_head ) ;
int data ; }
int hasrt ;
struct thtree *rc ;
};
main( )
{
struct thtree *th_head ;
th_head = NULL ;
insert ( &th_head, 11 ) ;

Data Structures Through C / Lecture 48 2


insert ( struct thtree **h, int num )
{ Empty
struct thtree *z ; *h
z = ( struct thtree * ) malloc (
sizeof ( struct thtree ) ) ; - 9999
z -> hasrt = z -> haslt = TRUE ; z
z -> data = num ;
if ( *h == NULL ) 11
{
*h = ( struct thtree * ) malloc ( sizeof ( struct thtree ) ) ;
( *h ) -> hasrt = ( *h ) -> haslt = FALSE ;
( *h ) -> lc = z ;
( *h ) -> data = - 9999 ;
( *h ) -> rc = *h ;
z -> rc = z -> lc = *h ;
return ;
} Contd...

...Contd
p = ( *h ) -> lc ; Non-Empty
struct thtree *p *h
while ( p != *h )
{ - 9999
if ( p -> data > num ) p
{
if ( p -> haslt == FALSE )
p = p -> lc ; z 11
else
{ 8
z -> lc = p -> lc ;
z -> rc = p ;
p -> lc = z ;
p -> haslt = FALSE ;
return ;
}
} Contd...

...Contd
if ( p -> data < num ) Non-Empty
{ *h
if ( p -> hasrt == FALSE )
p = p -> rc ; - 9999
else p
{
z -> rc = p -> rc ;
z -> lc = p ; p 11
p -> rc = z ;
p -> hasrt = FALSE ; 8
return ; z
}
}
} 10
}

Data Structures Through C / Lecture 48 3


inorder ( struct thtree *h ) *h p
{
struct thtree *p ;
p = h -> lc ; - 9999
while ( p != h ) pp
{
while ( p -> haslt == FALSE ) p 27 p
p = p -> lc ;
printf ( "%d ", p -> data ) ;
while ( p -> hasrt == TRUE ) 4 29
{ pp
p = p -> rc ;
if ( p == h ) 19
break ; pp
printf ( "%d ", p -> data ) ;
} p 7 p
p = p -> rc ;
}
} 5 13

Data Structures Through C / Lecture 48 4


Heap
Yashavant Kanetkar

Objectives
What is a heap
How to construct a heap
How to perform the heap sort

Heap
90 3

57 25 15 12

13 11 9 17 25 37 19

1 2 3 44 52

Max - heap or Min - heap or


descending heap ascending heap

Data Structures Through C / Lecture 49 1


Move L to L
Move L to R 11
Create Heap 11
P > LC, RC

2 9 13 9

13 57 25 17 2 57 25 17

1 90 3 1 90 3
13 57

11 9 13 25

2 57 25 17 2 11 9 17

1 90 3 1 90 3 Contd...

...Contd 57 57

13 25 13 25

2 11 9 17 90 11 9 17

1 90 3 1 2 3
57 90

90 25 57 25

13 11 9 17 13 11 9 17

1 2 3 1 2 3

Exercise 13
4

4 27
13 27
5 8
21 14 8
21 14 5 8

33
33 27
27

4 13 21 13

21 14 5 8 4 14 5 8

33 33 Contd...

Data Structures Through C / Lecture 49 2


...Contd
27
Exercise 27

21 13 21 13

4 14 5 8 33 14 5 8

33 4
27 33

33 13 27 13

21 14 5 8 21 14 5 8

4 4

Memorize highest index value


Replace it with root value Heap Sort
Determine bigger child
Shift it to root
Repeatedly compare in-mem no. with bigger child
Insert in-memory no. at proper place
57
90

13 25
57 25

3 11 9 17
13 11 9 17

1 2 3 1 2

57 13 25 3 11 9 17 1 2 90

90 57 25 13 11 9 17 1 2 3 Contd...

...Contd

57 25

13 25 13 17

3 11 9 17 3 11 9 2

1 2 1

25 13 17 3 11 9 2 1 57 90

57 13 25 3 11 9 17 1 2 90
Contd...

Data Structures Through C / Lecture 49 3


...Contd

25 17

13 17 13 9

3 11 9 2 3 11 1 2

17 13 9 3 11 1 2 25 57 90

25 13 17 3 11 9 2 1 57 90
Contd...

...Contd

17 13

13 9 11 9

3 11 1 2 3 2 1

13 11 9 3 2 1 17 25 57 90

17 13 9 3 11 1 2 25 57 90

Contd...

...Contd

13 11

11 9 3 9

3 2 1 1 2

11 3 9 1 2 13 17 25 57 90

13 11 9 3 2 1 17 25 57 90

Contd...

Data Structures Through C / Lecture 49 4


...Contd 11 9

3 9 3 2

1 2 1

9 3 2 1 11 13 17 25 57 90

11 3 9 1 2 13 17 25 57 90

3
3 1 2 9 11 13 17 25 57 90
1 2
Contd...

...Contd

3
3 1 2 9 11 13 17 25 57 90
1 2

2
2 1 3 9 11 13 17 25 57 90
1

1 1 2 3 9 11 13 17 25 57 90

1 2 3 9 11 13 17 25 57 90

Data Structures Through C / Lecture 49 5


AVL Trees &
B-Trees
Yashavant Kanetkar

Objectives
What are AVL trees
What are 2 - 3 trees
What are B - trees

Create Heap
# define MAX 10
main( )
{
int arr[ ] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i ;
createheap ( arr, MAX ) ;
printf ( "Heap: " ) ;
for ( i = 0 ; i < MAX ; i + + )
printf ( "%d\t", arr[ i ] ) ;
}

Data Structures Through C / Lecture 50 1


c
cp 11 p
createheap ( int *a, int n )
{ c
int val, i, c, p ; 2 9

for ( i = 1 ; i < n ; i + + )
{ 13 57 25 17
val = a[ i ] ;
c=i;
p=(c-1)/2; 1 90 3

while ( c > 0 && a[ p ] < val )


{
a[ c ] = a[ p ] ; c = p ;
p = (c - 1) / 2 ;
} pcpc c val = 13
a[ c ] = val ;
}
} 11 2 9 13 57 25 17 1 90 3

AVL Tree
1
Adelson - Velskii - Landis
13
Balanced Binary Tree
-1 1
5 19 Bal. Factor = ht. of left ST -
-1 ht. of right ST
0 0
3 9 16 struct AVL
{
0 struct AVL *lc ;
11 int balfact ;
int data ;
struct AVL *rc ;
};

2 - 3 Tree
20

6 15 24

3 5 9 17 22 27 33
Max. 2 values, min. 1 value
Non - leaf node must have max. 3 children, min. 2
children
All the leaf nodes should appear on the same level
Value(s) at left child < value(s) at middle child
Value(s) at middle child < value(s) at right child
If i and j are 2 values on same node then i < j
- all values on left child < i
- all values on middle child > i & < j
- all values on right child > j

Data Structures Through C / Lecture 50 2


B - Tree
27 42

Order - 4
2 13 22 32 37 40 47 51

Non - leaf nodes (except root) have min. n / 2 children,


max. n children
Node with n children must have n - 1 values
All the values of a particular node are in increasing
order
All the leaf nodes should appear on the same level
Values present on any child between any two values i &
j should be > i & < j, where i < j
Values present on left child must be < 1st value
Values present on right child must be > last value

Data Structures Through C / Lecture 50 3


Graphs
Yashavant Kanetkar

Objectives
What are graphs
The terminology associated with graphs
Representation of graphs
Adjacency list

Graphs 1
1

2 3 2

4
3

Undirected Graph Digraph


Graph is set of v & e
v - vertices (finite & non-empty), e - edges (pair of vertices)
Undirected graph - edge is unordered, (1, 2) & (2, 1) are same
Digraph - edge is ordered, <1, 2> & <2, 1> are different
In <1, 2> 1 is tail and 2 is head
In undirected graph 1 and 2 are adjacent
In undirected graph edge (1, 2) is incident on 1 & 2
In digraph 2 is adjacent to 3, while 3 is adjacent from 2
In digraph edges <1, 2> and <2, 1> are incident to 1 & 2

Data Structures Through C / Lecture 51 1


More Terminology
1
1 4 1 2

2
2 3
2 3
3 Strongly connected
components

Path - from 1 to 3 is sequence of vertices


1, 4, 3 with edges (1, 4), (4, 3)
Simple path - starting & ending vertex distinct. 1, 4, 3
Cyclic path - starting & ending vertex is same. 1, 2, 4, 1
Connected - if there is a path from v1 to v2
Strongly connected - if there is a path from v1 to v2 and v2 to v1.

Graph Representation
1 1

2 3
2
Store only
4 upper triangular
1 2 3 4 3
1 0 1 0 1 1 2 3
2 1 0 1 1 1 0 1 0
3 0 1 0 0 2 1 0 1
4 1 1 0 0 3 0 0 1

Adjacency Matrices

Adjacency List
V1 2 4 N
1
V2 1 3 4 N
2 3
V3 2 N
4
V4 1 2 N

1
V1 2 N

2
V2 1 3 N

V3 3 N
3

Data Structures Through C / Lecture 51 2


Exercise 1

V1 2 3 N 2 3

V2 1 4 5 N 4 5 6 7
V3 1 6 7 N
8
V4 2 8 N 1 2 3 4 5 6 7 8
1 0 1 1 0 0 0 0 0
V5 2 8 N 2 1 0 0 1 1 0 0 0
3 1 0 0 0 0 1 1 0
V6 3 8 N 4 0 1 0 0 0 0 0 1
5 0 1 0 0 0 0 0 1
V7 3 8 N 6 0 0 1 0 0 0 0 1
7 0 0 1 0 0 0 0 1
V8 4 5 6 7 N 8 0 0 0 1 1 1 1 0

Data Structures Through C / Lecture 51 3


Adjacency
Multilist
Yashavant Kanetkar

Objectives
Adjacency matrices
Adjacency multilist
Orthogonal representation of graphs

Adjacency Multilist
1 V1 2 3 4 N
V2 1 3 4 N
2 3
V3 1 2 4 N
4 V4 1 2 3 N

Next link Next link


m Vi Vj for Vi for Vj

1 V1 E1 1 2 E2 E4
E1 E2
E3 V2 E2 1 3 E3 E4 V1: E1-> E2 -> E3
2
E4
3 E3 1 4 N E V2: E1-> E4 -> E5
5
V3
E5 E6 E4 2 3 E5 E6 V3: E2-> E4 -> E6
4 V4
E5 2 4 N E V4: E3-> E5 -> E6
6

E6 3 4 N N

Data Structures Through C / Lecture 52 1


Adjacency Multilist
1 V1 2 N
E1 E2 V2 1 3 N

2 V3 2 N

E4 E3
Next link Next link
3 m tail head for tail for head

V1h E1 1 2 N E4 V1h : E2
V1t V1t : E1
V2h E2 2 1 E3 N V2h : E1 -> E4
V2t
E3 2 3 E2 N V2t : E2 -> E3
V3h V3h : E3
V3t E4 3 2 N E1 V : E4
3t

Exercise
1 6

2 5

3 4

Orthogonal Representation
1 2 3
1
1 0 1 0
2 1 0 1
2
3 0 0 0
col. link row link
3 tail head for head for head

head node 1 2 3

1 1 2 N N

2 2 1 N 2 3 N N

3 N

Data Structures Through C / Lecture 52 2


Exercise
1

2 4

Exercise
Give all graphical representations for the following graph

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

Adjacency Matrices

Adjacency List

1 2 V1 2 3 N

V2 1 N
3 5

4 V3 2 N

V4 3 5 N

V5 2 4 N

Data Structures Through C / Lecture 52 3


1 E1
E3
Adjacency Multilist
E2 2
E4
E8
3 E7 5
V1h E1 1 2 E2 E4
E5 4 V1t
E6 E2 1 3 E1 E5
V2h
V1h: E3 V2t E3 2 1 N N
V1t : E1 -> E2 V3h
E4 3 2 N E8
V2h: E1 -> E4 -> E8 V3t
V2t : E3 V4h E5 4 3 E6 E2
V3h: E2 -> E5 V4t
E6 4 5 E5 N
V3t : E4 V5h
V4h: E7 V5t E7 5 4 E8 N
V4t : E5 - > E6
V5h: E6 E8 5 2 E7 E1
V5t : E7 -> E8

1 E1
E3
Adjacency Multilist
E2 2
E4
E8
3 E7 5
V1h E1 1 2 E2 E4
E5 4 V1t
E6 E2 1 3 E1 E5
V2h
V1h: E3 V2t E3 2 1 N N
V1t : E1 -> E2 V3h
E4 3 2 N E7
V2h: E1 -> E4 -> E7 V3t
V2t : E3 V4h E5 4 3 E6 E2
V3h: E2 -> E5 V4t
E6 4 5 E5 N
V3t : E4 V5h
V4h: E8 V5t E7 5 2 E8 E1
V4t : E5 - > E6
V5h: E6 E8 5 4 E7 N
V5t : E7 -> E8

Orthogonal
1 1 2 3 4 5
2 1 0 1 1 0 0
2 1 0 0 0 0
3 5 3 0 1 0 0 0
4 0 0 1 0 1
4 5 0 1 0 1 0
head node 1 2 3 4 5

1 1 2 1 3 N

2 2 1 N

3 3 2 N
4 4 3 N 4 5N N

5 5 2 N 5 4 N N

Data Structures Through C / Lecture 52 4


Depth First
Search
Yashavant Kanetkar

Objectives
Study Depth First Search

Depth First Search Visit a vertex, mark it visited


Visit its adj. unvisited vertex
V1 2 3 N Rep. 1-2 till all adj. Ver. visited
Go back, repeat 1, 2 & 3
V2 1 4 5 N

V3 1 6 7 N 1

V4 2 8 N 2 3

V5 2 8 N
4 5 6 7
V6 3 8 N

V7 3 8 N 8

V8 4 5 6 7 N

Data Structures Through C / Lecture 53 1


Exercise
V1 2 8 N

V2 1 3 8 N
1 2 3
V3 2 4 8 N

V4 3 7 N 7 8

V5 6 7 N
6 5 4
V6 5 N

V7 4 5 8 N

V8 1 2 3 7 N

Program
# include "alloc.h" v1 = add ( 1 ) ;
#define MAX 8 v2 = add ( 4 ) ;
struct node v3 = add ( 5 ) ;
{ arr[ 1 ] = v1 ;
int data ; v1 -> next = v2 ;
v2 -> next = v3 ;
struct node *next ;
}; v1 = add ( 1 ) ;
struct node * add ( int ) ; v2 = add ( 6 ) ;
main( ) v3 = add ( 7 ) ;
{ arr[ 2 ] = v1 ;
struct node *arr[ MAX ] ; v1 -> next = v2 ;
struct node *v1, *v2, *v3 ; v2 -> next = v3 ;

v1 = add ( 2 ) ; v1 = add ( 2 ) ;
v2 = add ( 3 ) ; v2 = add ( 8 ) ;
arr[ 0 ] = v1 ; arr[ 3 ] = v1 ;
v1 -> next = v2 ; v1 -> next = v2 ; Contd...

...Contd
v1 = add ( 2 ) ; arr[ 7 ] = v1 ;
v2 = add ( 8 ) ; v1 -> next = v2 ;
arr[ 4 ] = v1 ; v2 -> next = v3 ;
v1 -> next = v2 ; v3 -> next = v4 ;
v1 = add ( 3 ) ; struct node *v4
v2 = add ( 8 ) ;
arr[ 5 ] = v1 ; dfs ( 1, arr, visited ) ;
v1 -> next = v2 ; int visited[ MAX ] = { 0 } ;
v1 = add ( 3 ) ;
v2 = add ( 8 ) ; for ( i = 0 ; i < MAX ; i++ )
arr[ 6 ] = v1 ; del ( arr[ i ] ) ; int i
v1 -> next = v2 ; }
v1 = add ( 4 ) ;
v2 = add ( 5 ) ;
v3 = add ( 6 ) ;
v4 = add ( 7 ) ;

Data Structures Through C / Lecture 53 2


add( )
struct node * add ( int val )
{
struct node *n ;
n = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
n -> data = val ;
n -> next = NULL ;
return n ;
}
New Node
n

5 N

dfs ( int v, struct node **p, int *pv ) 1


{
struct node *q ;
2 33
pv[ v - 1 ] = 1 ;
printf ( "%d\t", v ) ;
q=*(p+v-1); 4 5 6 7
while ( q != NULL )
{
if ( pv[ q -> data - 1 ] == 0 )
dfs ( q -> data, p, pv ) ; 8
else q
q = q -> next ; *p
}
} arr[ 0 ] 2 3 N
q q
1 2 4 8 5 6 3 7
arr[ 1 ] 1 4 5
1 2 3 4 5 6 7 8
arr[ 2 ] 1 6 7
01 01 01 0
1 0
1 0
1 0
1 0
1

del( )
del ( struct node *n )
{
struct node *t ;
while ( n != NULL )
n n t t = NULL
{
t = n -> next ; 2 3 N
arr[ 0 ]
free ( n ) ;
n=t;
} arr[ 1 ] 1 4 5 N
}
arr[ 2 ] 1 6 7 N

arr[ 3 ] 2 8 N

arr[ 4 ] 2 8 N

Data Structures Through C / Lecture 53 3


Breadth First
Search
Yashavant Kanetkar

Objectives
Study Breadth First Search

Breadth First Search 1

V1 2 3 N 2 3

V2 1 4 5 N 4 5 6 7

V3 1 6 7 N
8
V4 2 8 N 1 2 3 4 5 6 7 8

V5 2 8 N Visit a vertex, mark it visited


Add it to queue
Visit its adj. unvisited vertex
V6 3 8 N Add it to queue
Rep. 3-4 till all adj. Ver. Visited
V7 3 8 N Pick a vertex from queue
Rep. 1-6 till q becomes empty
V8 4 5 6 7 N

Data Structures Through C / Lecture 54 1


Exercise
V1 2 8 N
1 2 3
V2 1 3 8 N

7 8
V3 2 4 8 N

V4 3 7 N
6 5 4
V5 6 7 N

V6 5 N 1 2 8 3 7 4 5 6

V7 4 5 8 N

V8 1 2 3 7 N

bfs ( int v, struct node **p, int *pv ) 1


{ 1
struct node *u ;
2 3
struct queue q ; 1 2 3 4
q.f = q.r = -1 ; 01 0 0 0
pv[ v - 1 ] = 1 ; 4 5 6 7
printf ( "%d\t", v ) ; queue
addqueue ( &q, v ) ; 1
while ( isempty ( &q ) == 0 ) 8
{ u
v = delqueue ( &q ) ; *p
u=*(p+v-1);
arr[ 0 ] 2 3 N
struct queue
{
int q[ MAX ] ; arr[ 1 ] 1 4
int f, r ;
}; arr[ 2 ] 1 6
Contd...

...Contd while ( u != NULL ) 1 2 3 4 5 6 7 8


{
if ( pv [ u -> data - 1 ] == 0 ) queue
{
addqueue ( &q, u -> data ) ; 2 3 4 5
pv [ u -> data - 1 ] = 1 ;
printf ( "%d\t", u -> data ) ;
}
u = u -> next ; 01 01 01 10 01 01 01 0
1
}
1 u u
} *p
}
2 33 arr[ 0 ] 2 3 N
u u u
4 arr[ 1 ] 1 4 5
5 6 7
arr[ 2 ] 1 6 7

8 2 8 N
arr[ 3 ]

Data Structures Through C / Lecture 54 2


addqueue( )
addqueue ( struct queue *pq, int vertex )
{
if ( pq -> r == MAX - 1 )
{
printf ( "\Full." ) ;
exit( ) ;
}

pq -> r + + ;
pq -> q[ pq -> r ] = vertex ;

if ( pq -> f == - 1 )
pq -> f = 0 ;
}

delqueue( ) & isempty( )


delqueue ( struct queue *pq ) isempty ( struct queue *pq )
{ {
int data ; if ( pq -> f == - 1 )
return 1 ;
if ( pq -> f == - 1 ) return 0 ;
{ }
printf ( "\nEmpty." ) ;
exit( ) ;
}
data = pq -> q[ pq -> f ] ;
if ( pq -> f == pq -> r )
pq -> f = pq -> r = -1 ;
else
pq -> f + + ;
return data ;
}

Data Structures Through C / Lecture 54 3


Spanning Tree
Yashavant Kanetkar

Objectives
Spanning Tree
Cost of Spanning Tree
Kruskal’s Algorithm to determine minimum cost
Spanning Tree

Spanning Tree
Undirected tree
Contains edges necessary to connect all vertices

1 1 1

2 5 3 2 5 3 2 5 3

4 4 4
Spanning Trees
1 1

2 5 3 2 5 3

4 4
DFS ST BFS ST

Data Structures Through C / Lecture 55 1


Calculating Cost
4
1 4
7 2 1

2 3
3
4 4 4
1 4 1 4 1 4 1 4
1 2 7 1 7

2 3 2 3 2 3 2 3
3 3 3 3
4
1 4
Minimum Cost
2 1 Spanning Tree
2 3

Kruskal’s Algo • Insert edges in inc. order of cost


• Reject if it forms a cyclic path

4 Edge Cost Tree Action


1 4
1 4
7 2 1 4-3 1 1 Included
2 3 2 3
3

1 4
4
1 4 4-2 2 2 1 Included
2 1 2 3

2 3 4
3-2 3 1 4 Rejected
Minimum Cost 2 1
Spanning Tree 4-1 4 2 3 Included
3

Exercise Edge Cost Tree Action


A
A
13 10 B C
9
B C
20 D

40 D 35 E
14
A

E B C

Contd...

Data Structures Through C / Lecture 55 2


...Contd A Edge Cost Tree Action
13 10
9 A
B C
20
B C
40 D 35
14 D

E
E

A A
10
B 9 B C
C
20 D D

14
Min. E
Cost ST E

Data Structures Through C / Lecture 55 3


Dijkstra’s
Algorithm
Yashavant Kanetkar

Objectives
Dijkstra’s Algorithm to determine minimum cost
Spanning Tree
AOV Network
Topological Order
AOE Network

Dijkstra’s Algorithm
7
4
1 4
2
5 7 1

2 3
3

1 2 3 4 1 2 3 4

1 7 5 1 11 12 - -
2 7 2 2 21 - - 24
3 3 3 - 32 - -
4 4 1 4 41 - 43 -

Contd...

Data Structures Through C / Lecture 56 1


...Contd 7
4
1 4
2
5 7 1

2 3
3
1 2 3 4 1 2 3 4
1 7 5 1 11 12 - -
2 7 2 2 21 - - 24
3 3 3 - 32 - -
4 4 1 4 41 - 43 -
1 2 3 4 1 2 3 4
1 7 5 1 11 12 - -
2 7 12 2 2 21 212 - 24
3 3 3 - 32 - -
4 4 9 1 4 41 412 43 -

...Contd 7
4
1 4
2
5 7 1

2 3
1 2 3 4 3
1 2 3 4
1 7 5 1 11 12 - -
2 7 12 2 2 21 212 - 24
3 3 3 - 32 - -
4 4 9 1 4 41 412 43 -

1 2 3 4 1 2 3 4
1 7 5 7 1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 9 1 11 4 41 412 43 4124

...Contd 7
4
1 4
2
5 7 1

2 3
3
1 2 3 4 1 2 3 4
1 7 5 7 1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 9 1 11 4 41 412 43 4124
1 2 3 4 1 2 3 4
1 7 5 7 1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 4 1 6 4 41 432 43 4324

Data Structures Through C / Lecture 56 2


...Contd 7
4
1 4
2
5 7 1

2 3
3
1 2 3 4 1 2 3 4
1 7 5 7 1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 4 1 6 4 41 432 43 4324
1 2 3 4 1 2 3 4
1 7 5 8 7 1 11 12 1243 124
2 6 6 3 2 2 241 2432 243 24
3 9 3 6 5 3 3241 32 3243 324
4 4 4 1 6 4 41 432 43 4324

20 Exercise
8
E F
15 6 E F G E F G
G
7 E 8 15 E - EF EG
F 20 6 F FE - FG
G 7 G GE - -

E F G E F G
E 8 15 E - EF EG
F 20 28 6 F FE FEF FG
G 7 15 22 G GE GEF GEG

Contd...

...Contd
20
8
E F
15 6
G
7
E F G E F G
E 8 15 E - EF EG
F 20 28 6 F FE FEF FG
G 7 15 22 G GE GEF GEG

E F G E F G
E 28 8 14 E EFE EF EFG
F 20 28 6 F FE FEF FG
G 7 15 21 G GE GEF GEFG
Contd...

Data Structures Through C / Lecture 56 3


...Contd 20
8
E F
15 6
G
7
E F G E F G
E 28 8 14 E EFE EF EFG
F 20 28 6 F FE FEF FG
G 7 15 21 G GE GEF GEFG

E F G E F G
E 21 8 14 E EFGE EF EFG
F 13 21 6 F FGE FGEF FG
G 7 15 21 G GE GEF GEFG

Sub. No.
S1
Prereq.
None
Sub. No.
S8
Prereq.
S4
AOV N/W
S2 S1, S14 S9 S3 Activity On Vertex Network
S3 S1, S14 S10 S3, S4
S11 S10 V - Activity / Task
S4 S1, S13 E - Precedence Relation
S12 S11
S5 S15 S13 None
S6 S3 S14 S13
S7 S3, S4, S10 S15 S14
S13 S14 S15 S5

S4 S8 S2 S9

S1 S3 S6
Precedence
Activity
S7
S10
S11 S12

Exercise - I
Vertex Prerequisite V2
V1
V2
V3
V1 V3 V5
V4
V5
V6
V6

V4

Data Structures Through C / Lecture 56 4


Exercise - II
Vertex Prerequisite V2
V1
V2
V3
V1 V3 V5
V4
V5
V6
V4 V6

Not Feasible

Data Structures Through C / Lecture 56 5


Memory
Management-I
Yashavant Kanetkar

Objectives
Study Memory Management
Study First Fit Algorithm
Study Best Fit Algorithm

Memory Management
P1 P2 P3 P4 P5 Free

P1 Free P3 Free P5 Free


Size of block
Link

0 10000 20000 30000 0


Head Node

Each node contains


- size
- link
- free block

Data Structures Through C / Lecture 57 1


First Fit
av q p p

0 10000 5000
20000 30000 0

av q p

0 10000 0
20000 30000 0

Algo. - First Fit


av q p p

firstfit ( *av, n, *p )
{ 0 10000 5000
20000 30000
p = q = link ( av ) ;
while ( p != 0 )
{ n = 15000
if ( size ( p ) >= n )
{ q=p;
setsize ( p, size ( p ) - n ) ; p = link ( p ) ;
if ( size ( p ) == 0 ) }
setlink ( q, link ( p ) ) ; }
else
p = p + size ( p ) ;
break ;
}

Data Structures Through C / Lecture 57 2


Memory
Management-II
Yashavant Kanetkar

Objectives
Study Next Fit Algorithm

Best Fit
Disadv. of firstfit Algo.
Tendency to create too many small nodes
Search always starts at beginning of available list

av q p

0 50000 0
10000 30000 0

Data Structures Through C / Lecture 58 1


av qqpp q p pp p
Algo. - Best Fit
bestfit ( *av, n, *p )
{ 0 20000 5000
10000
p = q = link ( av ) ;
diff = 100000 ;
found = false ;
while ( p != 0 ) n = 5000
{ if ( found == true )
if ( size ( p ) >= n ) {
q = qq ; p = pp ;
{
d = ( size ( p ) - n ) ; setsize ( p, size( p ) - n ) ;
if ( d < diff ) if ( size ( p ) == 0 )
{ setlink ( q, link ( p ) ) ;
pp = p ; qq = q ;
else
found = true ;
p = p + size ( p ) ;
diff = d ; }
}
else
}
q = p ; p = link ( p ) ; printf ( "Insuff. mem." );
} }

Next Fit
llink tag = 0 size rlink tag = 1 size

tag = 0 uplink tag = 1


Free Node Allocated Node
p

llink tag = 0 3000 rlink tag = 1 7000

tag = 0 uplink tag = 1


Free Allocated

Algo. - Next Fit


av

0 500 0 700 0 900

0 0 0

nextfit ( *av, n, p )
q = llink ( p ) ; r = rlink ( p ) ;
{
p = rlink ( av ) ; alpha = 50 ; setlink ( rlink ( q ), r ) ;
while ( 1 ) setlink ( link ( r ), q) ;
{ settag ( p, 1 ) ;
if ( size ( p ) >= n ) settag ( p + size ( p ) - 1, 1) ;
{ av = llink ( p ) ;
diff = ( size ( p ) - n ) ; }
if ( diff < alpha )
{
Contd...

Data Structures Through C / Lecture 58 2


...Contd p p

llink tag = 0 600 rlink tag = 1 500

else tag = 0 uplink tag = 1


{ Free Allocated
setsize ( p, diff ) ; p = rlink ( p ) ;
setuplink ( p + size ( p ) - 1, p ) ; if ( p == rlink ( av ) )
settag ( p + diff - 2, 0 ) ; break ;
av = p ; }
p = p + diff ; p=0;
setsize ( p, n ) ; }
settag ( p, 1 ) ;
settag ( p + n - 1, 1 ) ;
}
break ;
}

Data Structures Through C / Lecture 58 3


Garbage
Collection
Yashavant Kanetkar

Objectives
Study Garbage Collection and Compaction

Garbage Collection
Method of detecting & reclaiming free nodes
Done in two phases:
Marking Phase - marks all nodes that are
accessible from an external
pointer ( nodes in use )
Collection Phase - free all nodes that
are not marked

Data Structures Through C / Lecture 59 1


Marking Phase
mark tag
t t t N

f 1 t t N

Atomic Node
f 4 f 3
marker( )
{
for each pointer x such that x != NULL
{
x -> mark = t ;
if ( x -> tag == t )
mark1 ( x ) ;
}
}

mark1 ( *x )
{
Algorithm Of Mark
top = 0 ; xp qp q
push ( stack, top, x ) ;
while ( top > 0 )
t t t t t
{
pop ( stack, top, p ) ;
while ( 1 ) t f 1 t t t
{
q = p -> link ;
p t f 4 q
if ( q != NULL )
{ if ( p -> mark == t
if ( q -> tag == t && || p -> tag == f )
q -> mark == f )
break ;
push ( stack, top, q ) ;
q -> mark = t ; p -> mark = t ;
} }
p = p -> dlink ; p -> mark = t ;
if ( p == NULL ) }
break ; }

GC & Compaction
size m link1 300 200
a 300 1500 200
nadd kr link2 T
1900
F
1000 1300
400 200 100
400 1000 200 1500 100
T 1900 T 1500 F
1500 1900 2100

300 400 200


300 1300 400 1000 200 1300
1000 T 1700 1300 T 1700 1700 T 1300
1000 1300 1700
200 100 Carried out in 3 steps
200 100 Determine new address
F F Update all links
1900 2100 Relocate nodes

Data Structures Through C / Lecture 59 2


Step - I
300 400 500
300 700 400 500 T 0
0 T 1200 F 300 1200
0 300 700
600 700
600 700 700
800 T 700 F
1200 1800
compact ( int m ) i = i + size ( i ) ;
{
i = av = 0 ; }
while ( i < m ) i av
{ 0 0
if ( mark ( i ) ) 300 300
{ 700 800
newadd ( i ) = av ; 1200 1200
av = av + size ( i ) ; 1800 1200
} 2500 1200

Step - II
300 400 500
300 300
700 400 500 T 0
0 T 1200
800 F 300 800
1200
0 300 700
600 700
600 T 300
700 700
800 300
700 F
1200 1800
i=0;
while ( i < m )
{
if ( mark ( i ) )
{
link1 ( i ) = newadd ( link1 ( i ) ) ;
link2 ( i ) = newadd ( link2 ( i ) ) ;
}
i = i + size ( i ) ;
}

Step - III
300 500 600
300 T 300 500 0 600 300
0 800 300 T 800 800 T 300
0 300 800
400 700
400 700
F F
1200 1600
i=0; p=0;
while ( i < m )
{
if ( mark ( i ) )
{
for ( j = i ; j < i + size ( i ) - 1 ; j + +, p + + )
mem[ p ] = mem [ j ] ;
}
i = i + size ( i ) ;
}
}

Data Structures Through C / Lecture 59 3


File
Organization
Yashavant Kanetkar

Objectives
Study File Organization

Files
Contains records
Records contain one or more fields
Each field represents an item of information
Purpose of file organization - Easy Retrieval and Updation
Retrieval using Primary or Secondary keys
Mode of Retrieval - Real time and Batched
Mode of Update - Real time or Batched

Data Structures Through C / Lecture 60 1


File Organization
Representing records on external storage medium
Sequential: New record inserted at end of file
Records might be of fixed or variable length
Insertion and Deletion is inefficient
Only Primary key ordering
Efficient for batch processing
Random: Records stored at random locations
Methods of access:
- Direct Addressing - Space inefficient
- Hashing - Easy Insertion and Deletion
- Multiple keys can be used in f( )
- Directory lookup - Indexed sequential access

Linked Organization:
Add. of next record is kept in current record
Easy insertion and deletion
Inefficient - As search is sequential
To improve efficiency - Range based index

Inverted: Multiple indexes


Record offsets matching an index is stored
with index itself

struct emp
{
Ind. Seq. Access
int id ;
char name[ 20 ] ;
int age ;
float sal ;
};

ID Rel. Off. ID Name Age Salary


121 0 121 Vishal 32 12000
125 28 125 Saurabh 24 4500
145 84 210 Sunil 24 5350
210 56 145 Shirish 22 4560
215 224 220 Shekhar 26 5670
218 252 245 Hetal 33 8790
220 112 234 Vipin 32 6780
234 168 266 Ashwini 22 3450
245 140 215 Sonal 21 3445
266 196 218 Shweta 28 8890

Data Structures Through C / Lecture 60 2