D ata Structures Through Csaintangelos.com/studentdesk/Download/YCMOU_Books/YCMOU... ·...

75
D a t a S t r u c t u r e s T h r o u g h C Student Workbook

Transcript of D ata Structures Through Csaintangelos.com/studentdesk/Download/YCMOU_Books/YCMOU... ·...

Data Structures Through C

Student Workbook

i

ContentsLecture 1: C Revision I 01

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 03

Pointers and their usage

Function call – by value and by reference

Arrays and their working

Lecture 3: Searching 05

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 07

Analyzing an algorithm

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

Lecture 5: Analysis of Searching Method 09

Tools to calculate time complexity

Cases to be considered while analyzing an algorithm

Analysis of Linear search and Binary search

Lecture 6: Hashing 11

Hashing techniques:

o Division method

o Mid-Square method

o Folding method

o Digit analysis method

Linear and Quadratic probing

ii

Lecture 7: Sorting 13

Selection sort and its analysis

Bubble sort and its analysis

Radix sort

Lecture 8: Sorting and Recursion 15

Insertion sort

Recursive functions

Lecture 9: Quick Sort 17

Splitting mechanism

Quick sort algorithm

Quick sort program

Lecture 10: Structures 19

Defining and using structures

Array of structures

Copying structure variables

Nested structures

Passing structure elements

Passing structures

Lecture 11: Structures and Polynomials 21

Polynomial representation

Passing array of structures

General operations on polynomials

Lecture 12: Two Dimensional Arrays 23

Using two dimensional arrays

Saddle point of an array

Lecture 13: Sparse Matrices 25

Sparse matrices

Passing arrays

3 tuple conversion

Lecture 14: Transpose of Sparse Matrices 27

Transpose of a sparse matrix

Lecture 15: Addition of Sparse Matrices 29

Addition of sparse matrices

Lecture 16: Multiplication of Sparse Matrices 31

Matrix multiplication

iii

Multiplication of sparse matrices

Lecture 17: Storage 33

Storage - two dimensional arrays

3 dimensional arrays

4 dimensional arrays

n - dimensional arrays

Lecture 18: Dynamic memory allocation 35

Limitations of arrays

Dynamic memory allocation

Steps involved in memory allocation

Lecture 19: Linked Lists 37

Memory leaks

Linked lists

Creation of linked lists

Lecture 20: Operations on Linked Lists I 39

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 41

Arranging the elements in a linked list in ascending order

Sorting the elements in a linked list

Lecture 22: Operations on Linked Lists – III 43

Reversing a linked list

Merging two linked lists

Lecture 23: Operations on Linked Lists – IV 45

Concatenating two linked lists

Addition of polynomials using linked lists

Lecture 24: Circular Linked Lists 47

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

iv

Lecture 25: Doubly Linked Lists 49

Doubly linked lists

Common operations on a doubly linked list

Lecture 26: Sparse Matrices as Linked Lists I 51

Representing sparse matrices in the form of linked lists

Lecture 27: Sparse Matrices as Linked Lists II 53

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 55

Recursive count( )

Recursive compare( )

Recursive copy( )

Recursive append( )

Lecture 29: Linked Lists Using Unions 57

What are unions

Declaring unions

Using unions

Generalized linked lists

Lecture 30: Generalized Linked Lists 59

Copying generalized linked lists

Depth of generalized linked lists

Comparing generalized linked lists

Lecture 31: Stacks 61

Stack and its utilities

Program to implement stack as an array

Lecture 32: Stack as a Linked List 63

Program to implement stack as a linked list

Lecture 33: Stack Expressions 65

Different form of expressions

Lecture 34: Stack Operations 67

Infix to Postfix conversion

Lecture 35: Postfix 69

Evaluation of Postfix form

v

Lecture 36: Infix To Prefix 71

Infix to Prefix conversion

Lecture 37: Postfix To Prefix 73

Evaluation of Prefix form

Postfix to Prefix conversion

Lecture 38: Postfix To Infix 75

Postfix to Infix conversion

Lecture 39: More Conversions 77

Prefix to Postfix conversion

Prefix to Infix conversion

Lecture 40: Queue I 79

Queue

Program to implement queue as an array

Lecture 41: Queue II 81

Limitations of queue

Circular queue

Lecture 42: Deque and Priority Queue 83

Deque

Program to implement deque

Priority queue

Lecture 43: Trees 85

What are trees

Tree terminology

Strictly and complete trees

Lecture 44: Tree Traversal 87

Preorder, Postorder and Inorder traversal

Reconstruction of trees

Lecture 45: Binary Search Trees I 89

Representing trees using arrays

Linked representation of trees

Binary search trees

Lecture 46: Binary Search Trees II 91

Traversing of trees using Inorder, Preorder and Postorder

Non recursive Inorder traversal of trees

Non recursive Preorder traversal of trees

vi

Non recursive Postorder traversal of trees

Comparison of two trees

Lecture 47: Binary Tree 93

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 95

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 97

Heap

Creation of a heap

Heap sort

Lecture 50: AVL Trees and B Tree 99

Program to create a heap

AVL tree

2 - 3 tree

B tree

Lecture 51: Graphs 101

Graphs

Terminology associated with graphs

Representation of graphs

Adjacency list

Lecture 52: Adjacency Multilist 103

Adjacency matrices

Adjacency multilist

Orthogonal representation of graphs

Lecture 53: Depth First Search 105

Depth first search

Program to implement depth first search algorithm

Lecture 54: Breadth First Search 107

Breadth first search

vii

Program to implement breadth first search algorithm

Lecture 55: Spanning Tree 109

What is a spanning tree

Cost of spanning tree

Kruskal’s algorithm to determine minimum cost spanning tree

Lecture 56: Dijkstra’s Algorithm 111

Dijkstra’s algorithm to determine minimum cost spanning tree

AOV network

Lecture 57: Memory Management I 113

Memory management

First fit algorithm

Best fit algorithm

Lecture 58: Memory Management II 115

Next fit algorithm

Lecture 59: Garbage Collection 117

Garbage Collection

Marking algorithm

Compaction

Lecture 60: File Organization 119

Files

File Organization

Data Structures Through C C Revision-I 1

C Revision-I Tips

(a) C supports three primary data types - int, char and float.

(b) The result of condition1 && condition2 is true, if both the operands are true, otherwise false.

(c) The output of condition1 || condition2 is false, if both the operands are false, otherwise true.

(d) There are three methods by way of which we can repeat a part of a program. They are:

Using a for statement

Using a while statement

Using a do-while statement

(e) The do-while tests the condition after having executed the statements within the loop at the least once.

Exercise[A] Fill In The Blanks:

(a) printf( ) and scanf( ) are ____________ whereas functions such as add( ) and delete( ) are ___________.

(b) The function is conveyed information through________.

(c) If the function returns no value then its declaration precedes the keyword____.

[B] What will be the output of the following:

(a) main( ) { int a [5] = { 5,1,15,20,25 } ; int i, j, k = 1, m ; i = ++a [1] ; j = a [1]++ ; m = a [ i++] ; printf ( “%d, %d, %d “, i, j, m ) ; }

(b) main( ) { static int count = 5 ; printf ( "\ncount = %d", count-- ) ; if ( count != 0 ) main( ) ; }

[D] Attempt the following:

(a) Write a program to calculate the sum of first 10 terms of the series:

1/1! + 2/2! + 3/3! + 4/4! ……

Data Structures Through C C Revision-II 3

C Revision-II Tips

(a) Data Structures is the way to organize the data and the operations performed on the data.

(b) In a call by value the ‘value’ of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function.

(c) In a call by reference the addresses of actual arguments in the calling function are copied into formal arguments of the called function.

(d) A variable that can hold multiple values is known as an array.

(e) The array elements are stored at adjacent memory locations.

Exercise[A] Fill In The Blanks:

(a) static int a [10] ; sets all elements of array to _____.

(b) Array of pointers contain________.

(c) In the declaration int *arr [100], arr acts as__________.

(d) The format specifier used to access the address of a variable is______.

[B] What will be the output of the following:

(a) main( ) { struct gospel { int num ; char mess1 [50] ; char mess2 [50] ; } m ; m.num = 1 ; strcpy ( m.mess1, "If all that you have is hammer" ) ; strcpy ( m.mess2, "Everything looks like a nail" ) ; /* assume that the strucure is located at address 1004 */ printf ( "\n%u %u %u", &m.num, m.mess1, m.mess2 ) ; }

(b) main( ) { int i = 4, j = -1, k = 0, w, x, y, z ; w = i || j || k ; x = i && j && k ; y = i || j && k ; z = i && j || k ; printf ( "\nw = %d x = %d y = %d z = %d", w, x, y, z ) ; }

4 C Revision-II Data Structures Through C

[D] Attempt the following:

(a) Implement sieve of Eratosthenes as per the following logic:

Step- 1 Fill an array num[100] with numbers from 1 to 100.

Step- 2 Starting with the second entry in the array, set all its multiples to step zero.

Step- 3 Proceed to the next non-zero element and set all its multiples to zero.

Step- 4 Repeat step 3 till you have set up the multiples of all the non-zero elements to zero.

Step- 5 At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.

(b) Write a program that will print out all the rotations of a string typed into it. For example, the rotations of the word "space" are:

space paces acesp cespa espac

Data Structures Through C Searching 5

Searching Tips

(a) An Array is a finite collection of similar elements stored in adjacent memory locations.

(b) The steps to solve a problem is known as an algorithm.

(c) In linear search method, the element is sequentially searched in the list.

(d) In binary search method, to search an element we compare it with the element present at the center of the list.

Exercise[A] State True or False:

(a) A data structure is said to be linear if its element form a sequence.

(b) Binary search always requires the list of elements be in sorted order.

(c) In linear search and binary search the list is always sorted.

[B] Fill In The Blanks:

(a) ________ and ________are the types of algorithms.

(b) While writing an algorithm we enclose the abbreviated description for the step within________.

(c) Important features of the algorithm are ______, ______, ______, ______, and ______.

(d) Each algorithm is given a name to identify which is written in _______.

Data Structures Through C Searching and Frequency Count 7

Searching and Frequency Count Tips

(a) When sum of cubes of each digit of a number is the number itself it is said to be an Armstrong number.

(b) The number of operations performed by an algorithm is directly proportional to the time taken to execute the algorithm.

Exercise[A] State True or False:

(a) While analyzing recursive algorithms we need to determine how many times the loop is executed.

(b) If the algorithm’s complexity is a combination of a two terms, we can safely ignore the slower growing term as per the rate of increase table.

(c) In linear search and binary search the list is always sorted.

[B] Fill In The Blanks:

(a) Traversing an array means_________.

(b) Accomplishing a task in finite number of steps is called as an__________.

(c) The time complexity for an iterative algorithm is determined by calculating the work done in the _______.

[C] Write algorithms and programs for the following:

(a) To reverse a given string.

(b) To get the biggest and smallest element in the given array.

Data Structures Through C Analysis of Searching Methods 9

Analysis of Searching Methods Tips

(a) Based on the order algorithms can be grouped into three categories:

Big Omega – ( f )

Big Oh – O ( f )

Big Theta – ( f )

(b) There are two average-cases for a linear search algorithm. The first assumes that the search is always successful and the other assumes that the value being searched will sometimes not be found.

(c) The maximum divisions required for binary search is log2 ( N+1 ).

Exercise [A] True or False:

(a) Big theta represents a class of functions that grow no faster than f.

(b) Rate of growth is dominated by largest term in the equation.

(c) Hashing is a sorting technique.

[B] Fill in the blanks:

(a) An algorithm on its order can be categorized as ______, _______and______.

(b) Function to measure the time complexity for an algorithm is_________ of machine architecture.

(c) __________ is dominated by largest term in an equation.

Data Structures Through C Hashing 11

Hashing Tips

(a) Hashing Functions are:

Division

Mid – Square

Folding

Digit Analysis

(b) The formula to evaluate a hash value in Linear probing is ( f ( x ) + i ) % b where:

f ( x ) is the hash value of the element obtained before linear probing,

i is the counter ranging between one to number of buckets, and

b is the total number of buckets.

(c) The formula to evaluate a hash value in quadratic probing is ( f ( x ) + i2 ) % b and ( f ( x ) - i2 ) % b where:

f ( x ) is the hash value of the element obtained before quadratic probing,

i is the counter ranging between one to number of buckets, and

b is the total number of buckets.

Exercise[A] True or False:

(a) When two identifiers hash into the same bucket it is called as Collision.

(b) Under mid square method for hashing we always calculate the binary equivalent of the number.

(c) The number of digits for hash value should always be 4 in Digit analysis method.

(d) Each bucket in the hash table can have several slots.

[B] Fill in the blanks:

(a) Collision Handling Techniques are ________and ________.

(b) __________ is hashing technique, which performs division.

(c) The average case analysis of linear search is __________.

(d) The worst case for binary search is ____________.

(e) _____________________ are used as the hash value in mid square method.

[C] Match the Following:

(a) Division of Array (1) Compile time memory allocation.

(b) Static memory allocation (2) Rehashing.

(c) Dynamic Memory allocation (3) Binary search

12 Hashing Data Structures Through C

(d) Collision handling (4) Big Oh Notation (e) Complexity measurement (5) Run time memory allocation [D] Write short notes:

(a) Quadratic probing

(b) Halving nature of binary search

(c) Big Oh notation

(d) Cases in analysis

Data Structures Through C Sorting 13

Sorting Tips

(a) To arrange the elements of a list in a particular order (ascending or descending) is called as Sorting.

(b) The elements compared in bubble sort are always adjacent.

(c) Under radix sort the elements are sorted using queues. The number of queues is equivalent to the base of the elements.

Exercise[A] Fill in the blanks:

(a) The elements compared in bubble sort are always________.

(b) The frequency count for selection sort and bubble sort is_____.

(c) The number of queues in radix sort depends on___________.

[B] What will be the output of the following programs:

(a) main( ) { int i ; for ( i = 0 ; i <= 50000 ; i++ ) printf ( "\n%d", i ) ; }

(b) int i = 0 ; main( )

{ printf ( "\nmain’s i = %d", i ) ; i++ ; val( ) ; printf ( "\nmain's i = %d", i ) ; val( ) ; }val( ) { i = 100 ; printf ( "\nval's i = %d", i ) ; i++ ; }

Data Structures Through C Sorting & Recursion 15

Sorting & Recursion Tips

(a) Insertion sort is implemented by inserting a particular element at the appropriate position.

(b) Recursion means a function that calls itself. Any function can be called recursively.

Exercise[A] Fill in the blanks:

(a) Recursion means a function that calls_______.

(b) If no condition is preceded with the recursive call then it becomes an_____.

(c) Recursive algorithms are also called as_____________ algorithms.

(d) To calculate the complexity for a divide and conquer algorithm the complexity for_______, ________, ________ and ________is required to be known.

(e) Recursion provides an elegant solution to the program but recursive function ________.

[B] What will be the output of the following programs:

(a) main( ) { int x, y, s = 2 ; s *= 3 ; y = f ( s ) ; x = g ( s ) ; printf ( "\n%d %d %d", s, y, x ) ; }int t = 8 ; f ( int a ) { a += -5 ; t -= 4 ; return ( a + t ) ; }g ( int a ) { a = 1 ; t += a ; return ( a + t ) ; }

(b) main( ) { int i, j ; for ( i = 1 ; i < 5 ; i++ ) { j = g ( i ) ; printf ( "\n%d", j ) ;

16 Sorting & Recursion Data Structures Through C

} }g ( int x ) { static int v = 1 ; int b = 3 ; v += x ; return ( v + x + b ) ;

}

[C] Attempt the following:

(a) A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

(b) Write a recursive function to obtain the first 20 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence:

1 1 2 3 5 8 13 21 34 55 89...

Data Structures Through C Quick Sort 17

Quick Sort Tips

(a) Quick sort works on the splitting mechanism or the divide and conquer mechanism.

(b) Quick sort is also known as partition exchange sort.

(c) One of the elements is considered as the pivot element and the sort aims at bringing this pivot to a position such that one array has elements less than the pivot and the other array has elements greater than the pivot.

(d) The pivot element is not necessarily the first element in the list.

(e) The best case for quick sort is when the list is divided each time in approximately two equal halves.

(f) Worst case time complexity for quick sort is O ( n2 ) that is similar to bubble and insertion sort.

(g) The best case time complexity is O ( log2 n ).

(h) Quick sort is better to insertion and bubble sort in average case.

Exercise[A] State True or False:

(a) The pivot element in quick sort is always the middle element in the list.

(b) Each pass in quick sort yields the pivot element to its final position in the list.

(c) In quick sort the list is rearranged in every pass such that all elements smaller than the pivot are moved before it and all elements larger than the pivot are moved after it.

(d) The number of comparisons made in worst case for quick sort is similar to radix sort and insertion sort.

(e) Swapping the elements in average case reduces 2n – 2 inversions in comparison to bubble sort and insertion sort.

(f) Time complexity of quick sort in average case is n2 and worst case is n log n.

(g) All sorting work in quick sort is done on the way back up in the recursive process.

(h) Quick sort is also known as partition exchange sort.

[B] Fill In The Blanks:

(a) In the function quicksort( ), a condition is checked whether ______ is greater than ______. If the condition is satisfied then only the array will be____ into two parts, otherwise, the control will simply be returned.

(b) The ______ loop is executed within the split( ) function that checks whether the indexes p and q________________.

(c) When the control returns to the function quicksort( ) _______________ are made to function quicksort( ).

(d) The efficiency of the quick sort method can be improved by__________, ______________, and _______________.

18 Quick Sort Data Structures Through C

[C] Attempt the following:

(a) If original list for quick sort is 6, 2, 4, 7, 1, 3, 8, 5 give the output produced by hand execution.

(b) If original list for quick sort is 15, 4, 10, 8, 6, 9, 16, 1, 7, 3, 11, 14, 2, 5, 12, 13 give the output produced by hand execution.

Data Structures Through C Structures-I 19

Structures-I Tips

(a) Instead of taking different arrays for different types of data, all the data items can be grouped together into one data type called structure.

(b) A structure is a collection of dissimilar elements.

(c) A structure is declared using struct keyword.

(d) Following the keyword struct, is the name of the structure or tag. Within the braces structure members / elements are declared.

(e) The structure elements are stored in contiguous memory locations.

Exercise[A] Point out the errors, if any:

(a) Look at the declarations below and point out the errors.

struct time { int hours ; int minutes ; int seconds ; } t ; struct time *tt ; tt = &t ; printf(“%d”, tt.seconds);

(b) Look at the code snippet below and point out the errors.

main( ) {

struct student { char name[20] ; int age; } ;

struct student s1 = { ”Rahul”, 10} ; struct student s2, s3 ; s2.name = s1.name ; s2.age = s1.age ; s3 = s1 ; printf ( ”%s %d”,s3.n,s3.a); }

[B] State True or False:

(a) All structure elements are stored in contiguous memory locations.

(b) An array should be used to store dissimilar elements, and a structure to store similar elements.

(c) In an array of structures, not only are all structures stored in contiguous memory locations, but also the elements of individual structures are also stored in contiguous locations.

20 Structures-I Data Structures Through C

(d) Nested structures are not allowed.

[C] Fill In The Blanks:

(a) The structure elements can be accessed by using the ____________ and ___________ operators.

(b) If the base address of an array of structures is passed to a function, it would be collected in a ________.

(c) If a structure pointer is to be used to access the structure elements, the ____ operator needs to be used.

(d) In the declaration of a structure the keyword _____ is followed by the _____ of the structure.

Data Structures Through C Structures-II 21

Structures-II Tips

(a) On incrementing a structure pointer, it is incremented by the sizeof the struct.

(b) All the members of one structure can be copied into another by simple assignment.

(c) A structure can be nested within another structure.

(d) If a structure is passed by reference, then the structure elements can be accessed by using the -> (arrow) operator.

Exercise[A] Attempt the following:

(a) Create a structure named india with structure elements as cityname, population, tot_literate.Now create a variable city that contains 50 elements of type india. Populate it with values and display only those citynames where literacy is 80% or more.

(b) Write a menu driven program which displays following menu:

sort by Salary sort by Designation

After selecting 1st option, list should be displayed accordingly. After selecting 2nd option list should be displayed but a subtotal of salary should also be displayed after each designation change. Fields to be displayed are name, designation, basic, hra, conveyance, salary.[Designations could be exec, mgr, sec, etc.].

(c) Create a structure called employee with data members as name, date_of_joining and salary.Write a program that accepts a date and displays a list of those employees whose tenure is 3 or more than 3 years from accepted date.

Data Structures Through C 2D Arrays 23

2D Arrays Tips

(a) If a lot of elements from a matrix have a value 0 then the matrix is known as a sparse matrix.

(b) A common way of representing non-zero elements of a sparse matrix is the 3-tuple forms.

Exercise[A] State True or False:

(a) If a lot of elements from a matrix have a value other than 0 then the matrix is known as a sparse matrix.

(b) There is a precise definition of when a matrix is sparse and when it is not.

Data Structures Through C Sparse Matrices 25

Sparse Matrices Tips

(a) In 3-tuple form each non-zero element is stored in a row, with the 1st and 2nd element of this row containing the row and column in which the element is present in the original matrix.

(b) The 3rd element in this row stores the actual value of the non-zero element.

Exercise[A] Pick up the correct alternative for each of the following questions:

(a) A matrix is called sparse when

(1) Most of its elements are non-zero. (2) Most of its elements are zero. (3) All of its elements are non-zero. (4) None of the above.

(b) A sparse matrix can be lower-triangular matrix

(1) When all the non-zero elements lie only on the leading diagonal. (2) When all the non-zero elements lie above leading diagonal. (3) When all the non-zero elements lie below leading diagonal. (4) Both (2) and (3).

[B] State True or False:

(a) A sparse matrix can be represented using a linked list.

(b) When addition or multiplication of sparse matrices is performed, it is not possible to predict the size of the resultant matrix.

(c) Tridiagonal matrix is the one in which the non-zero elements are placed below or above the leading diagonal.

Data Structures Through C Transpose Of Sparse Matrices 27

Transpose of Sparse Matrices Tips

(a) There are two ways in which information of a 3-tuple can be stored:

Arrays

Linked List

(b) In both representations information about the non-zero elements is stored.

Exercise[A] Fill In The Blanks:

(a) ____________ matrix is the one in which the non-zero elements are placed below or above the leading diagonal.

(b) A common way of representing non-zero elements of a sparse matrix is the ________ forms.

(c) The number of columns in the 3-tuple form would always be _____.

(d) In the 3-tuple form, the 0th column stores the ____ number, the 1st column stores the ____ number and the 2nd column stores the value of _____.

[B] Attempt the following: (a) Write a program to obtain the transpose of a matrix.

Data Structures Through C Addition Of Sparse Matrices 29

Addition of Sparse Matrices Tips

(a) As the number of non-zero elements in a sparse matrix may vary, it would be efficient to use a linked list to represent it.

(b) A sparse matrix, which is also a square matrix, can fall in the following categories:

Diagonal: Where the non-zero elements are stored on the leading diagonal of the matrix.

Tridiagonal: Where the non-zero elements are placed below or above the leading diagonal.

Lower Triangular: Where the non-zero elements are placed below the leading diagonal.

Upper Triangular: Where the non-zero elements are placed above the leading diagonal.

Exercise[A] Attempt the following:

(a) Write a program to subtract two sparse matrices implemented as an array.

(b) Write a program to multiply two sparse matrices implemented as an array.

Data Structures Through C Multiplication Of Sparse Matrices 31

Multiplication of Sparse Matrices

Tips(a) The prerequisite for matrix multiplication is that row number for one of the matrix is similar to

column number for another matrix.

(b) Since the array elements are stored in adjacent memory locations any element of the array can be accessed, once the base address of the array and number of rows and columns present in the array is known.

Exercise[A] State True or False:

(a) C language permits Row Major arrangement as well as the Column Major arrangement.

(b) Once the base address of the array and number of rows and columns present in the array is known, we can access the array elements easily.

(c) For an array a[m][n] as per Row Major arrangement the address of element a[i][j] would be Base address + j * m + i.

[B] Fill In The Blanks:

(a) The syntax used to declare a 2D array includes two subscripts, of which one specifies the number of _____ and the other specifies the number of ______ of the array.

(b) Arr[3][4] is an array containing ____ rows and _____ columns.

(c) When a 2D array is stored in the memory, the array elements are stored in _________ memory locations.

(d) The two possible arrangements of elements in the memory are ______________ arrangement and the ______________ arrangement.

Data Structures Through C Storage 33

Storage Tips

(a) When a 2D array gets stored in memory, all its elements are stored linearly.

(b) There are two possible arrangements of elements in memory Row Major arrangement and Column Major arrangement.

(c) In general for an array a[m][n] as per Row Major arrangement the address of element a[i][j] would be Base address + i * n + j.

(d) For an array a[m][n] as per Column Major arrangement the address of element a[i][j] would be Base address + j * m + i.

(e) C language permits only a Row Major arrangement.

Exercise[A] Attempt the following:

(a) Build an array called chess to represent a chessboard. Use 0 for black and 1 for white boxes.

(b) A square matrix is called symmetric if for all values of i and j, a[i][j] = a[j][i]. Write a program, which verifies whether a given 3 x 3 matrix is symmetric, or not.

(c) Find the location of the element a[1][2][2][1] from a 4D integer array a[4][3][4][3] if the base address of the array is 1002.

Data Structures Through C Dynamic Memory Allocation 35

Dynamic Memory Allocation Tips

(a) The size of the array remains fixed or static.

(b) We can dynamically allocate memory through the malloc( ) function.

(c) If there are lots of global variables used in a program, then the loader may fail in loading them.

(d) If too many local variables are present in our program then it may cause stack overflow.

Exercise[A] State True or False:

(a) The size of an array can be changed dynamically.

(b) Linked list is used to store similar data.

(c) All nodes in the linked list must always be in non-contiguous memory locations.

(d) It is necessary that the link part of the last node in a linked list must contain NULL.

Data Structures Through C Linked Lists 37

Linked Lists Tips

(a) In a linked list, each element points to the next element.

(b) Each element of the linked list is called a node.

(c) Each node consists of two parts viz., the data and the link to the next node.

(d) A linked list can hold integers, floats, strings or even multiple data types.

Exercise[A] Attempt the following:

(a) Write a program to add a new node at the end of the linked list.

(b) Write a program to find number of nodes in a linked list.

(c) Write a program to erase all the nodes of a linked list.

(d) Write a program to copy one linked list into another.

Data Structures Through C Operations on Linked Lists-I 39

Operations on Linked Lists I Tips

(a) Linked list is a very common data structure often used to store similar data in memory.

(b) Linked list is a collection of elements called nodes, each of which stores two items of information—an element of the list and a link.

(c) The elements of a linked list are not constrained to be stored in adjacent locations.

(d) A linked list can grow and shrink in size during its lifetime.

Exercise[A] State True or False:

(a) There is no maximum size of a linked list.

(b) The individual elements of a linked list are dispersed in memory.

[B] Attempt the following:

(a) Write a program to list the current directory in alphabetical order using a linked list.

Hints:

Use standard library functions findfirst( ) and findnext( ) in Turbo C to read the directory entries.

Define a structure struct node, which contains the standard structure struct ffblk defined in file "dos.h" as data part, and add another element next as link to the next node.

When all the directory entries are read and stored in the linked list, sort the linked list and then display the sorted linked list.

Data Structures Through C Operations on Linked Lists-II 41

Operations on Linked Lists-II Tips

(a) As nodes (elements) of a linked list are stored at different memory locations it hardly happens that we fall short of memory when required.

(b) Unlike arrays, while inserting or deleting the nodes of the linked list, shifting of nodes is not required.

(c) The order of the elements of linked list is maintained by explicit links between them.

(d) Various types of operations can be performed on a linked list. For example, adding new nodes at the beginning, at the end or in the middle of the linked list, displaying and counting the nodes of the linked list, deleting a node form the linked list, deleting all the nodes in the linked list, sorting the elements in the list etc.

Exercise[A] State True or False:

(a) The elements of a linked list must be in a sorted order.

(b) Sorting of the elements of the linked list can be performed by keeping the data in the nodes intact and just by readjusting the links between the nodes.

[B] Attempt the following:

(a) Write a program that reads the name, age and salary of 10 persons and maintains them in a linked list sorted by name.

(b) There are two linked lists A and B containing the following data:

A: 3, 7, 10, 15, 16, 9, 22, 17, 32.

B: 16, 2, 9, 13, 37, 8, 10, 1, 28.

Write a program to create:

A linked list C that contains only those elements that are common in linked list A and B.A linked list D that contains all elements of A as well as B ensuring that there is no repetition of

elements.

Data Structures Through C Operations on Linked Lists-III 43

Operations on Linked Lists III Tips

(a) All elements of a linked list can be accessed by first setting up a pointer pointing to the first node in the list and then traversing the entire list using this pointer.

(b) Concatenation of two linked lists means appending one list at the end of the other.

Exercise[A] State True or False:

(a) In a linked list, if we lose the location of the first node then it is as good as having lost the entire linked list.

(b) Polynomials cannot be stored using a linked list.

[B] Attempt the following: (a) There are two linked lists A and B containing the following data:

A: 7, 5, 3, 1, 20

B: 6, 25, 32, 11, 9

Write a function to combine the two lists such that the resulting list contains nodes in the following elements:

7, 6, 5, 25, 3, 32, 1, 11, 20, 9 You are not allowed to create any additional node while writing the function.

Data Structures Through C Operations on Linked Lists-IV 45

Operations on Linked Lists IV Tips

(a) Some of the operations that are carried out on linked lists can be easily implemented using recursion.

(b) Polynomials can also be represented using linked lists.

(c) It is possible to carry out various polynomial operations like polynomial addition etc using the linked lists.

Exercise[A] Attempt the following:

(a) Create two linked lists to represent the following polynomials:

9 x3 + 3 x2 + 15 x + 3 13 x3 + 7 x2 + 22 x + 9Write a function add( ) to add these polynomials and print the resulting linked list.

Data Structures Through C Circular Linked Lists 47

Circular Linked Lists Tips

(a) In a circular linked list, if we begin at a given node and traverse the entire list, we ultimately end up at the starting point.

(b) A circular linked list can be used to represent a stack and a queue.

(c) A circular linked list has no knowledge about where the previous node lies in memory.

Exercise[A] State True or False:

(a) If a pointer p points to a node in a linked list, we cannot reach any of the nodes that precede the node to which p is pointing.

(b) If a pointer p is pointing to one of the nodes in a circular linked list, then moving the pointer to the next node would cause a memory leak.

Data Structures Through C Doubly Linked Lists 49

Doubly Linked Lists Tips

(a) In a doubly linked list, along with the address of next node, the address of the previous node in the linked list is also stored in each node of the linked list.

(b) In a doubly linked list, we can traverse the list in the forward as well as in the backward direction from a given intermediate node in the list.

(c) While adding a new node to a doubly linked list, both the links to the previous node as well as the next node have to be set.

Exercise[A] State True or False:

(a) Doubly linked list facilitates movement from one node to another in either direction.

(b) A doubly linked list will occupy less space as compared to a corresponding singly linked list.

(c) If we were to traverse from last node to first node it would be easier to do so if the linked list is singly linked instead of doubly linked.

(d) In a structure used to represent the node of a doubly linked list it is necessary that the structure elements are in the order backward link, data, forward link.

[B] Attempt the following:

(a) Write a program to add a new node to a doubly linked list.

(b) Write a program to count the nodes present in a doubly linked list.

(c) Write a program to delete an existing node from a doubly linked list.

(d) Write a program to add a node at the beginning of a doubly linked list.

(e) Write a program to add a node at a specified position in a doubly linked list.

Data Structures Through C Sparse Matrices as Linked List-Is 51

Sparse Matrices as Linked Lists I

Tips(a) When we carry out addition or multiplication of sparse matrix using the 3-tuple array

representation, it is not possible to predict beforehand how many elements in the resultant matrix would be non-zero.

(b) Instead of an array, we can represent the sparse matrix in the form of a linked list.

(c) In the linked list representation a separate list is maintained for each column as well as each row of the matrix.

(d) A node in a list stores the information about the non-zero element of the sparse matrix.

(e) The head node for a column list stores the column number, a pointer to the node, which comes first in the column, and a pointer to the next column head node.

Exercise[A] Pick up the correct alternative for the following:

(a) In the linked representation of a sparse matrix the head node for a column list stores

(1) A pointer to the next column head node. (2) A pointer to the first node in column list. (3) Column number. (4) All of the above.

[B] Fill In The Blanks:

(a) If a particular column list is empty then the field down of the column head node would be _______.

(b) If a row list is empty then the field _________ of the row head node would be empty.

(c) A node in a list stores the information about the __________ element of the sparse matrix.

(d) The information stored in this special node is used for _____________.

Data Structures Through C Sparse Matrices as Linked Lists-II 53

Sparse Matrices as Linked Lists-II

Tips(a) Similarly, a head node for a row list stores, a pointer to the node, which comes first in the row

list, and a pointer to the next row head node.

(b) A node stores the row number, column number and the value of the non-zero element of the sparse matrix.

(c) The node also stores a pointer to the node that is immediately to the right of it in the row list as well as a pointer to the node that is immediately below it in the column list.

(d) In addition to this a special node is used to store the total number of rows, total number of columns, a pointer to the first row head node and a pointer to the first column head node.

(e) The information stored in this special node is used for traversing the list.

Exercise[A] Attempt the following:

(a) Write a program to build a sparse matrix as a linked list.

(b) Write a program that provides functions for following operations on a sparse matrix represented as a linked list:

(i) Store an element when the row number, column number and the value are provided. (ii) Retrieve an element for given row and column number of the matrix.

Data Structures Through C Linked List Using Recursion 55

Linked List Using Recursion Tips

(a) In C, it is possible for the functions to call themselves.

(b) A function is called 'recursive' if a statement within the body of a function calls the same function.

(c) Recursion is also called 'circular definition'.

(d) Recursion is the process of defining something in terms of itself.

Exercise[A] Fill In The Blanks:

(a) A function is called _________ if a statement within the body of a function calls the same function.

(b) ___________ is also called 'circular definition'.

[B] Attempt the following:

(a) Using recursion write a program to find number of nodes in a linked list that represents a polynomial.

Data Structures Through C Linked List Using Unions 57

Linked List Using Unions Tips

(a) Unions are derived data types, the way structures are.

(b) Both structures and unions are used to group a number of different variables together.

(c) A union offers a way for a section of memory to be treated as a variable of one type on one occasion, and as a different variable of a different type on another occasion.

(d) The union elements are accessed exactly the same way in which the structure elements are accessed, using a ‘.’ operator.

(e) When a two-byte number is stored in memory, the low byte is stored before the high byte.

Exercise[A] What will be the output of the following programs: (a) main( )

{ union { int i[2] ; long l ; } u ;

u.i[0] = 0x50 ; u.i[1] = 0x45 ; printf ( "\n%lu", u.l ) ; }

(b) main( ) { union a { int i1 ; int i2 ; char s[4] ; } ; union a m ; strcpy ( a.s, "AAA" ) ; printf ( "\n%s", a.s ) ; printf ( "\n%u %u", a.i1, a.i2 ) ; }

[B] State True or False:

(a) We can’t assign different values to the different union elements at the same time.

(b) When a two-byte number is stored in memory, the high byte is stored before the low byte.

58 Linked List Using Unions Data Structures Through C

(c) A union variable occupies as much data as what a corresponding structure variable would occupy, elements of both remaining same.

(d) Union provides us a way to look at the same memory locations in more than one way, which a structure cannot.

(e) It is possible to have nested unions.

(f) A union in a structure, or a structure in a union is not allowed.

[C] Fill In The Blanks:

(a) The union elements are accessed using a ________ operator.

(b) We can access the elements of the union in a structure using the _________ operator twice.

Data Structures Through C Generalized Linked List 59

Generalized Linked List Tips

(a) We can’t assign different values to the different union elements at the same time.

(b) Just as one structure can be nested within another, a union too can be nested in another union.

(c) There can be a union in a structure, or a structure in a union.

(d) The depth of the empty generalized list is defined to be zero.

Exercise[A] Fill In The Blanks:

(a) When a two-byte number is stored in memory, the _______ byte is stored before the _____ byte.

[B] Attempt the following:

(a) Using recursion write a program to copy one polynomial represented as a linked list into another.

(b) Using recursion write a program to add a new node at the end of the linked list.

Data Structures Through C Stacks 61

Stacks Tips

(a) A Stack is a data structure in which addition of new element or deletion of an existing element always takes place at the same end.

Exercise[A] Fill in the blanks:

(a) A stack is a data structure in which addition of new element or deletion of an existing element always takes place at an end called ______.

(b) The data structure stack is also called _____________ structure.

Data Structures Through C Stacks As Linked List 63

Stacks As Linked List Tips

(a) The arithmetic expressions can be written in three forms:

Infix

Postfix

Prefix

(b) While writing an arithmetic expression, the operator symbol is usually placed between two operands. This is called as infix notation.

Exercise[A] Pick up the correct alternative for each of the following questions:

(a) Adding an element to the stack means

(1) Placing an element at the front end. (2) Placing an element at the top. (3) Placing an element at the rear end. (4) None of the above.

(b) Pushing an element to a stack means

(1) Removing an element from the stack. (2) Searching a given element in the stack. (3) Adding a new element to the stack. (4) Sorting the elements in the stack.

(c) Popping an element from the stack means

(1) Removing an element from the stack. (2) Searching a given element in the stack. (3) Adding a new element to the stack. (4) Sorting the elements in the stack.

Data Structures Through C Stack Expressions 65

Stack Expressions Tips

(a) While evaluating an infix expression usually the following operator precedence is used:

Highest priority: Exponentiation ( $ )

Next highest priority: Multiplication ( * ) and Division ( / )

Lowest priority: Addition ( + ) and Subtraction ( - )

Exercise[A] Fill in the blanks:

(a) In __________ notation the operators precedes the two operands.

(b) In __________ notation the operator follows the two operands.

[B] Transform the following infix expressions into their equivalent postfix expressions:

(a) ( A - B ) * ( D / E )

(b) ( A + B ^ D ) / ( E - F ) + G

Data Structures Through C Stack Operations 67

Stack Operations Tips

(a) In prefix notation the operator comes before the operands.

(b) In postfix notation, the operator follows the operands.

Exercise[A] Write programs for the following:

(a) Copying contents of one stack to another.

Data Structures Through C Postfix 69

Postfix Tips

(a) While evaluating postfix expression, the expression is scanned from left to right.

Exercise[A] True or False:

(a) Stack is of fixed size.

(b) The expressions within a pair of parentheses are always evaluated earlier than other operations.

(c) Every character of the infix expression to be converted to postfix expression is scanned from right to left.

(d) If character scanned is an operand, then it is directly added to the target expression.

Data Structures Through C Infix To Prefix 71

Infix To Prefix Tips

(a) While evaluating prefix expression, the expression is scanned from right to left.

Exercise[A] Fill in the blanks:

(a) A stack is generally implemented with two basic operations: ____________________.

(b) The place where stacks are frequently used is _________________________________.

(c) The _______________________ used in an arithmetic expression represent the operations like addition, subtraction, multiplication, division and exponentiation.

(d) While evaluating an infix expression, the highest priority operator is _____________________.

(e) In postfix to prefix conversion, the expression in postfix form is scanned from ______________.

Data Structures Through C Postfix To Prefix 73

Postfix To Prefix Tips

(a) In the conversion from postfix to prefix, while concatenating the operator with the two elements popped from the stack, the concatenation should be of the form operator s2 s1 where s1 is the first popped element and s2 is the 2nd popped element.

Exercise[A] Transform the following infix expressions into their equivalent prefix expressions:

(a) ( A - B ) * ( D / E )

(b) A * ( B + D ) / E - F * ( G + H / K )

Data Structures Through C Postfix To Infix 75

Postfix To Infix Tips

(a) In the conversion from postfix to infix, while concatenating the operator with the two elements popped from the stack, the concatenation should be of the form s2 operator s1 where s1 is the first popped element and s2 is the 2nd popped element.

Exercise[A] Transform each of the following postfix expression to infix:

(a) A B - C + D E F - + $

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

Data Structures Through C More Conversions 77

More Conversions Tips

(a) The expression in prefix form to be converted to postfix form is scanned from left to right.

(b) The expression in prefix to be converted to infix form is scanned from right to left.

Exercise[A] True or False:

(a) In prefix to infix conversion, we scan the expression from right to left.

Data Structures Through C Queue-I 79

Queue I Tips

(a) Queue is a linear data structure that permits insertion of new element at one end and deletion of an element at the other end.

(b) The first element that gets added into the queue is the first one to get removed from the list.

Exercise[A] True or False:

(a) Queue is a non-linear data structure.

(b) The first element that gets added into the queue is the last one to get removed from the list.

(c) Queue permits insertion of new element at one end and deletion of an element at the other end.

[B] Choose the correct alternative for the following:

(a) Queue is a

(1) Linear data structure. (2) Non-linear data structure. (3) Both (1) and (2). (4) None of the above.

(b) The end at which a new element gets added to a queue is called

(1) Front. (2) Rear. (3) Top. (4) Bottom.

(c) The end from which an element gets removed from the queue is called

(1) Front. (2) Rear. (3) Top. (4) Bottom.

(d) Queue is also called

(1) Last-In-First-Out data structure. (2) First-In-Last-Out data structure. (3) First-In-First-Out data structure. (4) Last-In-Last-Out data structure.

[C] Write programs for the following:

(a) Write a program to add elements to a queue implemented as a circular linked list.

(b) Write a program to delete elements from a queue implemented as a circular linked list.

Data Structures Through C Queue-II 81

Queue II Tips

(a) In the implementation of queue there is a possibility that the queue is reported as full, even though in actuality there might be empty slots at the beginning of the queue.

(b) A priority queue is a collection of elements where the elements are stored according to their priority levels.

(c) The order in which the elements should get added or removed is decided by the priority of the element.

Exercise[A] True or False:

(a) Deque is a generalization of both a stack and a queue.

(b) Queue can be represented only as linked lists.

[B] Fill in the blanks:

(a) The word __________________ is a short form of double-ended queue.

(b) A ________________________ is a collection of elements where the elements are stored according to their priority levels.

Data Structures Through C Deque & Priority Queue 83

Deque & Priority Queue Tips

(a) The circular queue would be reported as full only when all the slots in the array stand occupied.

(b) The word deque is a short form of double-ended queue.

(c) Deque is a data structure in which items can be added or deleted at either the front or rear end, but no changes can be made elsewhere in the list.

Exercise[A] True or False:

(a) The circular queue would be reported as full as soon as we reach the end of the array.

(b) If there are elements with the same priority, then the element added first in the queue would get processed.

[B] Fill in the blanks:

(a) The _____________________ would be reported as full only when all the slots in the array stand occupied.

(b) The element with a ______________________ priority is processed before any element of ________________________ priority.

[C] Write programs for the following:

(a) Write a program to copy one queue to another when the queue is implemented as a linked list.

(b) Write a program to implement priority queue as an array.

Data Structures Through C Trees 85

Trees Tips

(a) Trees and graphs are non-linear data structures.

(b) In a tree structure, each node may point to several other nodes, which in turn may point to several other nodes.

(c) Forest is a set of several trees that are not linked to each other in any way.

Exercise[A] State True or False:

(a) A binary tree whose non-leaf nodes have left and right child is a complete binary tree.

(b) The number of nodes attached to a particular node in a tree is called the degree of the node.

(c) Trees and graphs are non-linear data structures.

[B] Fill in the blanks:

(a) _____________________ is a set of several trees that are not linked to each other in any way.

(b) The children of a node are called as __________________________.

Data Structures Through C Tree Traversal 87

Tree Traversal Tips

(a) The number of nodes connected to a particular node is called the degree of a particular node.

(b) A complete binary tree of depth d is a strictly binary tree in which all the leaves of the tree are at the same level d.

(c) The methods of binary tree traversal are in-order traversal, pre-order traversal and post-ordertraversal.

Exercise[A] State True or False:

(a) While traversing a non-empty binary tree in pre-order traversal, we first visit the root, then the right sub tree and lastly the left sub tree.

(b) If every non-leaf node in a binary tree has non-empty left and right sub-trees, the tree is termed a strictly binary tree.

[B] Fill in the blanks:

(a) The methods of binary tree traversal are ________________ traversal, ________________ traversal and __________________________ traversal.

(b) The root of the tree has level ____________________.

(c) The ___________________ of a binary tree is the maximum level of any leaf in the tree.

[C] Answer the Following:

(a) Give the pre-order, post-order and in-order traversal steps of the following tree.

(b) Write a program to represent a binary tree using an array.

Data Structures Through C Binary Search Trees-I 89

Binary Search Tree-I Tips

(a) Trees are non-linear data structures.

(b) In a tree structure, each node may point to several other nodes (which may then point to several other nodes, etc.).

(c) Thus a tree is a very flexible and powerful data structure that can be used for a wide variety of applications.

(d) Although the nodes in a general tree may contain any number of pointers to the other tree nodes, a large number of data structures have at the most two pointers to the other tree nodes.

(e) This type of a tree is called binary tree.

(f) A binary tree is a finite set of elements that is either empty or is partitioned into three disjoint sub-sets.

Exercise[A] State True or False:

(a) Going from the leaves to the root is called climbing the tree, and going from the root to the leaves is called descending the tree.

(b) The degree of a leaf node is always one.

[B] Fill In The Blanks:

(a) If A is the root of a binary tree and B is the root of its left or right sub-tree. Then, A is said to be the ___________ of B.

(b) A node that has no sons is called a __________.

Data Structures Through C Binary Search Trees-II 91

Binary Search Tree II Tips

(a) The other two sub-sets are themselves binary trees, called the left and right sub-trees of the original tree.

(b) A left or right sub-tree can be empty.

(c) Each element of a binary tree is called a node of the tree.

(d) If every non-leaf node in a binary tree has non-empty left and right sub-trees, the tree is termed as strictly binary tree.

(e) The number of nodes connected to a particular node is called the degree of a particular node.

(f) The root of the tree has level 0, and the level of any other node in the tree is one more than the level of its father.

(g) The depth of a binary tree is the maximum level of any leaf in the tree.

(h) The traversal of a binary tree is to visit each node in the tree exactly once.

(i) There are three popular methods of binary tree traversal.

(j) These methods are known as in-order traversal, pre-order traversal and post-order traversal.

Exercise[A] State True or False:

(a) The degree of a leaf node is always one.

(b) A complete binary tree of depth d is a strictly binary tree all of whose leaves are at the same level d.

(c) A binary tree is recursive in that each sub-tree is really a binary tree itself.

[B] Fill In The Blanks:

(a) Two nodes are ___________ if they are left and right sons of the same father.

(b) The three popular methods of traversal are known as ___________traversal, ___________ traversal and ___________traversal.

[C] Attempt the following:

(a) Write a program that implements the non-recursive form of the functions inorder( ), preorder( )and postorder( ).

(b) Write a program that counts the number of nodes in a binary tree and the number of leaf nodes in a binary tree.

(c) Write a program to represent a binary tree using one single array using the array given below.

{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', '\0', '\0', 'H', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'

};

Data Structures Through C Binary Trees 93

Binary Trees Tips

(a) Both the recursive and non-recursive procedures for binary tree traversal require that pointers to all of the free nodes be kept temporarily on a stack.

(b) A procedure that does not require any pointers to the nodes be put on the stack eliminates the overhead (time and memory) involved in initializing, pushing and popping the stack.

(c) The pointers that point inorder successor of a node are called right threads.

(d) Each right thread replaces a normal right pointer in a tree node.

(e) We can have left threads that point to the inorder predecessor of a node.

(f) The only problem with threads is that the coding requires that we know whether a pointer is a normal pointer to a child or a thread that points back to an inorder successor or inorder predecessor node.

Exercise[A] State True or False:

(a) Each left thread replaces a normal left pointer in a tree node.

(b) If the data to be inserted in a BST is found to be greater than or equal to the data of the root node then the new node is inserted in the left sub-tree of the root node.

(c) While searching the data if the leaf node of tree is reached and the data is not found then it is concluded that the data is not present in the tree.

[B] Fill In The Blanks:

(a) If the data to be inserted in a BST is found to be less than the data of the root node then the new node is inserted in the __________ sub-tree of the root node.

(b) In a threaded binary tree the address of the inorder predecessor and inorder successor are stored in _____ and _____ child of the leaf node respectively.

Data Structures Through C Threaded Binary Trees 95

Threaded Binary Trees Tips

(a) Each node in a threaded binary tree would contain data, a left pointer, a true or false value for left thread, a right pointer and a true or false value for right thread.

(b) To insert any node into a BST, initially the data that is to be inserted is compared with the dataof the root node.

(c) If the data is found to be greater than or equal to the data of the root node then the new node is inserted in the right sub-tree of the root node, otherwise, the new node is inserted in the left sub-tree of the root node.

(d) To search any node in a binary tree, initially the data that is to be searched is compared with the data of the root node.

(e) If the data is equal to the data of the root node then the searching is successful.

(f) If the data is found to be greater than the data of the root node then the searching process proceeds in the right sub-tree of the root node, otherwise, searching process proceeds in the left sub-tree of the root node.

Exercise[A] Attempt the following:

(a) Write a program to search a node in a given threaded binary tree.

(b) Write a program to delete a node from a threaded binary tree.

Data Structures Through C Heap 97

Heap Tips

(a) Heap is a complete binary tree.

(b) There are two types of heaps. If the value present at any node is greater than all its children then such a tree is called as the max-heap or descending heap.

(c) In case of a min-heap or ascending heap the value present in any node is smaller than all its children.

(d) Frequent insertions and deletions in a binary search tree are likely to make it unbalanced.

(e) The efficiency of searching is ideal if the difference between the heights of left and right sub-trees of all the nodes in a binary search tree is at the most one.

Exercise[A] Attempt the following:

(a) Write a program to implement the heap sort algorithm.

Data Structures Through C AVL Trees & B-Trees 99

AVL Tree & B Tree Tips

(a) A binary search tree, in which the difference between the heights of left and right sub-trees is at the most one, is called AVL Tree.

(b) An AVL Tree is also known as Balanced Binary Tree.

(c) The balance factor of any node is calculated by subtracting the height of the right sub-tree of the node from the height of the left sub-tree.

(d) The value of balance factor of any node is -1, 0 or 1.

(e) The basic idea behind maintaining a search tree is to make the insertion, deletion and searching operations efficient.

(f) In AVL trees the searching operation is efficient.

(g) To eliminate the complications in insertion and deletion in AVL trees, a data structure called 2-3Tree can be used.

(h) To improve the efficiency of tree operations multi-way search trees can be used.

(i) A B – Tree is a multi-way tree of order n is a tree in which any node may contain maximum n - 1 values and can have maximum of n children.

Exercise[A] State True or False:

(a) The balance factor of any node is calculated by subtracting the height of the left sub-tree of the node from the height of the right sub-tree.

(b) If the value of balance factor of any node is other than –1, 0, 1 then the tree is not balanced or it is not an AVL tree.

(c) If the value of balance factor of any node is 0 then the height of its left and right sub-tree is different.

(d) In a 2 – 3 Tree, the level of all the leaf nodes must always be the same.

(e) In a B – Tree, all the non-leaf nodes (except the root node) have at least n/2 children and at the most n children.

[B] Fill In The Blanks:

(a) An ordered balanced binary tree is called a _________ where the value at the root of any sub-tree is less than or equal to the value of either of its children.

(b) In an AVL Tree, the difference between the heights of left and right sub trees is at the most _________.

(c) In the structure that represents an AVL tree, an additional field is required to hold the ____________.

100 AVL Trees & B-Trees Data Structures Through C

(d) If the value of balance factor of any node is -1, then the height of the right sub-tree of that node is one __________ than the height of its left sub-tree.

(e) One single node can contain either _________ or ________ values.

(f) The number of values that a particular node of a binary search tree or an AVL tree can hold is only ________.

(g) In a B – Tree, all the values of a particular node are in ___________ order.

(h) In any node of B-tree of order n the minimum required values and children are _____ and _____ respectively.

Data Structures Through C Graphs 101

Graphs Tips

(a) Graphs are data structures that have wide-ranging applications in real life.

(b) Graph is a non-linear data structure.

(c) A graph consists of two sets v and e where, v is a finite, non-empty set of vertices and e is a set of pairs of vertices.

(d) The pairs of vertices are called edges.

(e) A directed graph is also called digraph.

Exercise[A] State True or False:

(a) Graph is a non-linear data structure.

(b) In an undirected graph, the pairs (v1, v2) and (v2, v1) represent the same edge.

(c) A simple path is a path in which the first and last vertices are the same.

(d) The adjacency matrix for an undirected graph is symmetric.

[B] Fill In The Blanks:

(a) Two types of graphs are _________ graph and ____________ graph.

(b) The edges of a directed graph are drawn with an arrow from the _______ to the ________.

(c) If <1, 2> is a directed edge, then vertex 1 is said to be ___________ 2 while 2 is _________ 1.

(d) About half the space needed to represent a graph using its adjacency matrix can be saved in the case of undirected graphs by storing only the ___________or __________ triangle of the matrix.

Data Structures Through C Adjacency Multilist 103

Adjacency Multilist Tips

(a) In an undirected graph, the edge (v1, v2) is incident on vertices v1 and v2.

(b) If <v1, v2> is a directed edge, then vertex v1 is said to be adjacent to v2 while v2 is adjacent from v1.

(c) A simple path is a path in which all the vertices except the first and last are distinct.

(d) A cyclic path is a simple path in which the first and last vertices are the same.

(e) In an undirected graph, two vertices v1 and v2 are said to be connected if there is a path from v1to v2.

(f) An undirected graph is said to be strongly connected if for every distinct vertices vi, vj in the graph there is a path from vi to vj.

(g) A directed graph is said to be strongly connected if for every pair of distinct vertices vi, vj in the graph there is a directed path from vi to vj and also from vj to vi.

(h) The adjacency matrix of a graph is a 2-dimensional array of size n x n (where n is the number of vertices in the graph).

Exercise[A] Attempt the following:

(a) For the graph given below, give all graphical representations.

- Its adjacency matrix,

- Its adjacency list representation,

- Its adjacency multilist,

- Its orthogonal representation.

1

4

2

3

Data Structures Through C Depth First Search 105

Depth First Search Tips

(a) Depth First Search and Breadth First Search are the two algorithms, which are used to visit all the vertices from a given vertex in a directed or undirected graph.

(b) The most commonly used representations for graphs are adjacency matrices and adjacency lists.

(c) The adjacency matrix of G is a 2-dimensional array of size n x n (where n is the number of vertices in the graph) with the property that a[i][j] = 1 if the edge (vi , vj) is in the set of edges, and a[i][j] = 0 if there is no such edge.

Exercise[A] State True or False:

(a) If v1 and v2 are two vertices of a directed graph G, then the edges <v1, v2> and <v2, v1>represent the same edge.

(b) Depth First Search algorithm is used to visit all the vertices from a given vertex in a directed or undirected graph.

(c) The adjacency matrix for a directed graph is asymmetric.

(d) Breadth first search differs from depth first search in that all unvisited vertices adjacent to v, are visited next.

[B] Fill in the blanks:

(a) In adjacency lists representation the n rows of the adjacency matrix are represented as n ___________________________.

(b) The adjacency matrix for an undirected graph is __________________________.

(c) The pairs of vertices are called __________________________________.

(d) A directed graph is also called _________________________________.

Data Structures Through C Breadth First Search 107

Breadth First Search Tips

(a) The adjacency matrix for an undirected graph is symmetric.

(b) The adjacency matrix for a directed graph need not be symmetric.

(c) In adjacency lists representation the n rows of the adjacency matrix are represented as n linked lists.

Exercise[A] Answer the Following:

(a) What is the difference between the depth first search algorithm and breadth first search algorithm.

(b) Give the sequence of nodes to traverse the vertices of the following graph using Depth First Search and Breadth First Search.

Data Structures Through C Spanning Tree 109

Spanning Tree Tips

(a) A spanning tree of a graph is an undirected tree consisting of only those edges that are necessary to connect all the vertices in the original graph.

(b) A spanning tree has a property that for any pair of vertices there exists only one path between them.

(c) The cost of a spanning tree is the sum of costs of the edges in that tree.

Exercise[A] State True or False:

(a) It is the property of the spanning tree that for any pair of vertices there exists only one path between them.

(b) The cost of a spanning tree is the sum of costs of the edges in that tree.

(c) An edge is included in spanning tree if it forms a cycle with edges already in that tree.

(d) In Kruskal’s algorithm a minimum cost spanning tree T is built vertex by vertex.

(e) Vertex i in an AOV network is a predecessor of vertex j, if there is a directed path from vertex ito vertex j.

[B] Fill in the blanks:

(a) If i is a predecessor of vertex j, then j is a ________________________ of i.

(b) A path of longest length is a __________________________ path.

(c) All the activities for which e ( i ) = l ( i ) are called ________________________ activities.

(d) To find the minimum cost of spanning tree using Kruskal’s Algo the edges are inserted to tree in _______________________ order of their costs.

(e) The minimum cost of spanning tree is given by _____________________________________.

Data Structures Through C Dijkstra’s Algorithm 111

Dijkstra�s Algorithm Tips

(a) A directed graph in which the vertices (V) represent tasks or activities and the edges (E)represent precedence relations between tasks is an activity on vertex network or AOV – network.

(b) An activity network closely related to the AOV network is the activity on edge or AOE network.

Exercise[A] Answer the Following:

(a) Find the possible spanning trees for the graph.

Data Structures Through C Memory Management-I 113

Memory Management I Tips

(a) One of the most important function of operating system is memory management.

(b) Whenever the operating system needs to request memory, it must be able to allocate a block of contiguous storage of the right size.

(c) When the execution of the program is complete, operating system releases or frees the block of memory allocated to it and this freed block may be then allocated to another program.

Exercise[A] State True or False:

(a) It is the job of the process to search for the memory it requires.

(b) In the first fit, the first block of size greater than the requested size of memory is allocated.

[B] Fill in the blanks:

(a) In first fit and best fit, each node on the free list has the fields ______________, ____________________ and __________________________.

(b) _______________________ node is the zero size node.

(c) _________________________ leaves many small nodes in the available space.

Data Structures Through C Memory Management-II 115

Memory Management II Tips

(a) In the first fit, the first block of size greater than the requested size of memory is allocated.

(b) The best fit algorithm finds a free block whose size is as close to the requested size as possible, but not less than that.

Exercise[A] State True or False:

(a) Next fit combines smaller nodes in the free list to form a bigger block of memory.

(b) The node structure used in next fit is different from that used for first fit and best fit.

(c) In first fit the search for a node always begins at the front of the list.

[B] Fill in the blanks:

(a) _____________________ calls for finding a free block whose size is as close to the requested size as possible, but not less than that.

(b) The _________________ field in a free block is needed, only when returning a block whose left adjacent block is free.

[C] Answer the following:

(a) State the disadvantages of first fit algorithm.

Data Structures Through C Garbage Collection 117

Garbage Collection Tips

(a) Garbage collection is the process of collecting all unused nodes and returning them to the available space.

(b) In the first phase known as the marking phase, all nodes in use are marked.

(c) In collection phase, all unmarked nodes are returned to the available space list.

Exercise[A] State True or False:

(a) Compaction is desirable only for variable size nodes.

(b) Marking phase marks all nodes that are not accessible from an external pointer.

[B] Fill in the blanks:

(a) A _____________________ is a collection of records.

(b) The two phases in the process of garbage collection are __________________ and _________________.

Data Structures Through C File Organization 119

File Organization Tips

(a) Compaction is to compact memory, so that all free nodes form a contiguous block of memory.

(b) A file is a collection of records where each record consists of one or more fields representing item of information.

(c) A combination of key values specified for retrieval is termed a query.

Exercise[A] State True or False:

(a) When the file contains more than one key, it is not possible to use indexed sequential access method of file organization.

(b) In sequential file organization, only primary key ordering is possible.

(c) In inverted file organization, multiple indexes are used.

[B] Fill in the blanks:

(a) The mode of retrieval and update may be ______________________ or ______________________.

(b) The response time is significant in case of _________________ mode of retrieval.

(c) When the file extends over several disks, a ___________________ is also maintained.

[C] Answer the following: (a) Write a note on marking phase.

(b) Write a note on ISAM.