Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
122 views

Data Structure in C Book Programs

The document contains C code for programs that perform operations on arrays and matrices. It includes functions to insert and delete elements from arrays, reverse and display arrays, merge two arrays, and search an array. It also includes functions to create, add, multiply and transpose matrices, as well as display the contents of matrices. The main function demonstrates using these functions by performing sample operations on sample data.

Uploaded by

naznin18
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

Data Structure in C Book Programs

The document contains C code for programs that perform operations on arrays and matrices. It includes functions to insert and delete elements from arrays, reverse and display arrays, merge two arrays, and search an array. It also includes functions to create, add, multiply and transpose matrices, as well as display the contents of matrices. The main function demonstrates using these functions by performing sample operations on sample data.

Uploaded by

naznin18
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 210

/* CH2PR1.C: Program to implement an array. */ #include <stdio.h> #include <conio.

h> #define MAX 5 void insert ( int *, int pos, int num ) ; void del ( int *, int pos ) ; void reverse ( int * ) ; void display ( int * ) ; void search ( int *, int num ) ; void main( ) { int arr[5] ; clrscr( ) ; insert ( arr, 1, 11 ) ; insert ( arr, 2, 12 ) ; insert ( arr, 3, 13 ) ; insert ( arr, 4, 14 ) ; insert ( arr, 5, 15 ) ; printf ( "\nElements of Array: " ) ; display ( arr ) ; del ( arr, 5 ) ; del ( arr, 2 ) ; printf ( "\n\nAfter deletion: " ) ; display ( arr ) ; insert ( arr, 2, 222 ) ; insert ( arr, 5, 555 ) ; printf ( "\n\nAfter insertion: " ) ; display ( arr ) ; reverse ( arr ) ; printf ( "\n\nAfter reversing: " ) ; display ( arr ) ; search ( arr, 222 ) ; search ( arr, 666 ) ; getch( ) ; }

/* inserts an element num at given position pos */ void insert ( int *arr, int pos, int num ) { /* shift elements to right */ int i ; for ( i = MAX - 1 ; i >= pos ; i-- ) arr[i] = arr[i - 1] ; arr[i] = num ; } /* deletes an element from the given position pos */ void del ( int *arr, int pos ) { /* skip to the desired position */ int i ; for ( i = pos ; i < MAX ; i++ ) arr[i - 1] = arr[i] ; arr[i - 1] = 0 ; } /* reverses the entire array */ void reverse ( int *arr ) { int i ; for ( i = 0 ; i < MAX / 2 ; i++ ) { int temp = arr[i] ; arr[i] = arr[MAX - 1 - i] ; arr[MAX - 1 - i] = temp ; } } /* searches array for a given element num */ void search ( int *arr, int num ) { /* Traverse the array */ int i ; for ( i = 0 ; i < MAX ; i++ ) { if ( arr[i] == num ) { printf ( "\n\nThe element %d is present at %dth position.", num, i+1); return ; } }

if ( i == MAX ) printf ( "\n\nThe element %d is not present in the array.", num ) ; } /* displays the contents of a array */ void display ( int *arr ) { /* traverse the entire array */ int i ; printf ( "\n" ) ; for ( i = 0 ; i < MAX ; i++ ) printf ( "%d\t", arr[i] ) ; }

/* CH2PR2.C: Program to merge two 1-D arrays. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define MAX1 5 #define MAX2 7 int *arr ; int* create ( int ) ; void sort ( int *, int ) ; void display ( int *, int ) ; int* merge ( int *, int * ) ; void main( ) { int *a, *b, *c ; clrscr( ) ; printf ( "\nEnter elements for first array: \n\n" ) ; a = create ( MAX1 ) ; printf ( "\nEnter elements for second array: \n\n" ) ; b = create ( MAX2 ) ; sort ( a, MAX1 ) ; sort ( b, MAX2 ) ;

printf ( "\nFirst array: \n" ) ; display ( a, MAX1 ) ; printf ( "\n\nSecond array: \n" ) ; display ( b, MAX2 ) ; printf ( "\n\nAfter Merging: \n" ) ; c = merge ( a, b ) ; display ( c, MAX1 + MAX2 ) ; getch( ) ; } /* creates array of given size, dynamically */ int* create ( int size ) { int *arr, i ; arr = ( int * ) malloc ( sizeof ( int ) * size ) ; for ( i = 0 ; i < size ; i++ ) { printf ( "Enter the element no. %d: ", i + 1 ) ; scanf ( "%d", &arr[i] ) ; } return arr ; } /* sorts array in ascending order */ void sort ( int *arr, int size ) { int i, temp, j ; for ( i = 0 ; i < size ; i++ ) { for ( j = i + 1 ; j < size ; j++ ) { if ( arr[i] > arr[j] ) { temp = arr[i] ; arr[i] = arr[j] ; arr[j] = temp ; } } } } /* displays the contents of array */

void display ( int *arr, int size ) { int i ; for ( i = 0 ; i < size ; i++) printf ( "%d\t", arr[i] ) ; } /* merges two arrays of different size */ int* merge ( int *a, int *b ) { int *arr ; int i, k, j ; int size = MAX1 + MAX2 ; arr = ( int * ) malloc ( sizeof ( int ) * ( size ) ) ; for ( k = 0, j = 0, i = 0 ; i <= size ; i++ ) { if ( a[k] < b[j] ) { arr[i] = a[k] ; k++ ; if ( k >= MAX1 ) { for ( i++ ; j < MAX2 ; j++, i++ ) arr[i] = b[j] ; } } else { arr[i] = b[j] ; j++ ; if ( j >= MAX2 ) { for ( i++ ; k < MAX1 ; k++, i++ ) arr[i] = a[k] ; } } } return arr ; }

/* CH2PR3.C: Program to perform operations like addition, multiplicaton, etc. on matrix. */ #include <stdio.h> #include <conio.h> #define MAX 3 void create ( int [3][3] ) ; void display ( int [3][3] ) ; void matadd ( int [3][3], int [3][3], int [3][3] ) ; void matmul ( int [3][3], int [3][3], int [3][3] ) ; void transpose ( int [3][3], int [3][3] ) ; void main( ) { int mat1[3][3], mat2[3][3], mat3[3][3], mat4[3][3], mat5[3][3] ; clrscr( ) ; printf ( "\nEnter elements for first array: \n\n" ) ; create ( mat1 ) ; printf ( "\nEnter elements for second array: \n\n" ) ; create ( mat2 ) ; printf ( "\nFirst Array: \n" ) ; display ( mat1 ) ; printf ( "\nSecond Array:\n" ) ; display ( mat2 ) ; matadd ( mat1, mat2, mat3 ) ; printf ( "\nAfter Addition: \n" ) ; display ( mat3 ) ; matmul ( mat1, mat2, mat4 ) ; printf ( "\nAfter Multiplication: \n" ) ; display ( mat4 ) ; transpose ( mat1, mat5 ) ; printf ( "\nTranspose of first matrix: \n" ) ; display ( mat5 ) ; getch( ) ; }

/* creates matrix mat */ void create ( int mat[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) { printf ( "Enter the element: " ) ; scanf ( "%d", &mat[i][j] ) ; } } } /* displays the contents of matrix */ void display ( int mat[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) printf ( "%d\t", mat[i][j] ) ; printf ( "\n" ) ; } } /* adds two matrices m1 and m2 */ void matadd ( int m1[3][3], int m2[3][3], int m3[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) m3[i][j] = m1[i][j] + m2[i][j] ; } } /* multiplies two matrices m1 and m2 */ void matmul ( int m1[3][3], int m2[3][3], int m3[3][3] ) { int i, j, k ; for ( k = 0 ; k < MAX ; k++ ) {

for ( i = 0 ; i < MAX ; i++ ) { m3[k][i] = 0 ; for ( j = 0 ; j < MAX ; j++ ) m3[k][i] += m1[k][j] * m2[j][i] ; } } } /* obtains transpose of matrix m1 */ void transpose ( int m1[3][3], int m2[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) m2[i][j] = m1[j][i] ; } }

/* CH2PR3.C: Program to perform operations like addition, multiplicaton, etc. on matrix. */ #include <stdio.h> #include <conio.h> #define MAX 3 void create ( int [3][3] ) ; void display ( int [3][3] ) ; void matadd ( int [3][3], int [3][3], int [3][3] ) ; void matmul ( int [3][3], int [3][3], int [3][3] ) ; void transpose ( int [3][3], int [3][3] ) ; void main( ) { int mat1[3][3], mat2[3][3], mat3[3][3], mat4[3][3], mat5[3][3] ; clrscr( ) ; printf ( "\nEnter elements for first array: \n\n" ) ; create ( mat1 ) ;

printf ( "\nEnter elements for second array: \n\n" ) ; create ( mat2 ) ; printf ( "\nFirst Array: \n" ) ; display ( mat1 ) ; printf ( "\nSecond Array:\n" ) ; display ( mat2 ) ; matadd ( mat1, mat2, mat3 ) ; printf ( "\nAfter Addition: \n" ) ; display ( mat3 ) ; matmul ( mat1, mat2, mat4 ) ; printf ( "\nAfter Multiplication: \n" ) ; display ( mat4 ) ; transpose ( mat1, mat5 ) ; printf ( "\nTranspose of first matrix: \n" ) ; display ( mat5 ) ; getch( ) ; } /* creates matrix mat */ void create ( int mat[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) { printf ( "Enter the element: " ) ; scanf ( "%d", &mat[i][j] ) ; } } } /* displays the contents of matrix */ void display ( int mat[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) {

for ( j = 0 ; j < MAX ; j++ ) printf ( "%d\t", mat[i][j] ) ; printf ( "\n" ) ; } } /* adds two matrices m1 and m2 */ void matadd ( int m1[3][3], int m2[3][3], int m3[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) m3[i][j] = m1[i][j] + m2[i][j] ; } } /* multiplies two matrices m1 and m2 */ void matmul ( int m1[3][3], int m2[3][3], int m3[3][3] ) { int i, j, k ; for ( k = 0 ; k < MAX ; k++ ) { for ( i = 0 ; i < MAX ; i++ ) { m3[k][i] = 0 ; for ( j = 0 ; j < MAX ; j++ ) m3[k][i] += m1[k][j] * m2[j][i] ; } } } /* obtains transpose of matrix m1 */ void transpose ( int m1[3][3], int m2[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) m2[i][j] = m1[j][i] ; } }

/* CH2PR3.C: Program to perform operations like addition, multiplicaton, etc. on matrix. */ #include <stdio.h> #include <conio.h> #define MAX 3 void create ( int [3][3] ) ; void display ( int [3][3] ) ; void matadd ( int [3][3], int [3][3], int [3][3] ) ; void matmul ( int [3][3], int [3][3], int [3][3] ) ; void transpose ( int [3][3], int [3][3] ) ; void main( ) { int mat1[3][3], mat2[3][3], mat3[3][3], mat4[3][3], mat5[3][3] ; clrscr( ) ; printf ( "\nEnter elements for first array: \n\n" ) ; create ( mat1 ) ; printf ( "\nEnter elements for second array: \n\n" ) ; create ( mat2 ) ; printf ( "\nFirst Array: \n" ) ; display ( mat1 ) ; printf ( "\nSecond Array:\n" ) ; display ( mat2 ) ; matadd ( mat1, mat2, mat3 ) ; printf ( "\nAfter Addition: \n" ) ; display ( mat3 ) ; matmul ( mat1, mat2, mat4 ) ; printf ( "\nAfter Multiplication: \n" ) ; display ( mat4 ) ; transpose ( mat1, mat5 ) ; printf ( "\nTranspose of first matrix: \n" ) ; display ( mat5 ) ; getch( ) ; }

/* creates matrix mat */ void create ( int mat[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) { printf ( "Enter the element: " ) ; scanf ( "%d", &mat[i][j] ) ; } } } /* displays the contents of matrix */ void display ( int mat[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) printf ( "%d\t", mat[i][j] ) ; printf ( "\n" ) ; } } /* adds two matrices m1 and m2 */ void matadd ( int m1[3][3], int m2[3][3], int m3[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) m3[i][j] = m1[i][j] + m2[i][j] ; } } /* multiplies two matrices m1 and m2 */ void matmul ( int m1[3][3], int m2[3][3], int m3[3][3] ) { int i, j, k ; for ( k = 0 ; k < MAX ; k++ ) {

for ( i = 0 ; i < MAX ; i++ ) { m3[k][i] = 0 ; for ( j = 0 ; j < MAX ; j++ ) m3[k][i] += m1[k][j] * m2[j][i] ; } } } /* obtains transpose of matrix m1 */ void transpose ( int m1[3][3], int m2[3][3] ) { int i, j ; for ( i = 0 ; i < MAX ; i++ ) { for ( j = 0 ; j < MAX ; j++ ) m2[i][j] = m1[j][i] ; } }

/* CH2PR6.C: Program to multiply two polynomials. */ /#include <stdio.h> #include <conio.h> #define MAX 10 struct term { int coeff ; int exp ; }; struct poly { struct term t [10] ; int noofterms ; }; void initpoly ( struct poly *) ; void polyappend ( struct poly *, int, int ) ; struct poly polyadd ( struct poly, struct poly ) ; struct poly polymul ( struct poly, struct poly ) ;

void display ( struct poly ) ; void main( ) { struct poly p1, p2, p3 ; clrscr( ) ; initpoly ( &p1 ) ; initpoly ( &p2 ) ; initpoly ( &p3 ) ; polyappend ( &p1, 1, 4 ) ; polyappend ( &p1, 2, 3 ) ; polyappend ( &p1, 2, 2 ) ; polyappend ( &p1, 2, 1 ) ; polyappend ( &p2, 2, 3 ) ; polyappend ( &p2, 3, 2 ) ; polyappend ( &p2, 4, 1 ) ; p3 = polymul ( p1, p2 ) ; printf ( "\nFirst polynomial:\n" ) ; display ( p1 ) ; printf ( "\n\nSecond polynomial:\n" ) ; display ( p2 ) ; printf ( "\n\nResultant polynomial:\n" ) ; display ( p3 ) ; getch( ) ; } /* initializes elements of struct poly */ void initpoly ( struct poly *p ) { int i ; p -> noofterms = 0 ; for ( i = 0 ; i < MAX ; i++ ) { p -> t[i].coeff = 0 ; p -> t[i].exp = 0 ; } }

/* adds the term of polynomial to the array t */ void polyappend ( struct poly *p, int c, int e ) { p -> t[p -> noofterms].coeff = c ; p -> t[p -> noofterms].exp = e ; ( p -> noofterms ) ++ ; } /* displays the polynomial equation */ void display ( struct poly p ) { int flag = 0, i ; for ( i = 0 ; i < p.noofterms ; i++ ) { if ( p.t[i].exp != 0 ) printf ( "%d x^%d + ", p.t[i].coeff, p.t[i].exp ) ; else { printf ( "%d", p.t[i].coeff ) ; flag = 1 ; } } if ( !flag ) printf ( "\b\b " ) ; } /* adds two polynomials p1 and p2 */ struct poly polyadd ( struct poly p1, struct poly p2 ) { int i, j, c ; struct poly p3 ; initpoly ( &p3 ) ; if ( p1.noofterms > p2.noofterms ) c = p1.noofterms ; else c = p2.noofterms ; for ( i = 0, j = 0 ; i <= c ; p3.noofterms++ ) { if ( p1.t[i].coeff == 0 && p2.t[j].coeff == 0 ) break ; if ( p1.t[i].exp >= p2.t[j].exp ) { if ( p1.t[i].exp == p2.t[j].exp )

{ p3.t[p3.noofterms].coeff = p1.t[i].coeff + p2.t[j].coeff ; p3.t[p3.noofterms].exp = p1.t[i].exp ; i++ ; j++ ; } else { p3.t[p3.noofterms].coeff = p1.t[i].coeff ; p3.t[p3.noofterms].exp = p1.t[i].exp ; i++ ; } } else { p3.t[p3.noofterms].coeff = p2.t[j].coeff ; p3.t[p3.noofterms].exp = p2.t[j].exp ; j++ ; } } return p3 ; } /* multiplies two polynomials p1 and p2 */ struct poly polymul ( struct poly p1, struct poly p2 ) { int coeff, exp ; struct poly temp, p3 ; initpoly ( &temp ) ; initpoly ( &p3 ) ; if ( p1.noofterms != 0 && p2.noofterms != 0 ) { int i ; for ( i = 0 ; i < p1.noofterms ; i++ ) { int j ; struct poly p ; initpoly ( &p ) ; for ( j = 0 ; j < p2.noofterms ; j++ ) { coeff = p1.t[i].coeff * p2.t[j].coeff ; exp = p1.t[i].exp + p2.t[j].exp ;

polyappend ( &p, coeff, exp ) ; } if ( i != 0 ) { p3 = polyadd ( temp, p ) ; temp = p3 ; } else temp = p ; } } return p3 ; } /* CH3PR1.C: Program to perform some basic operations on string. */ #include <stdio.h> #include <conio.h> #include <string.h> int xstrlen ( char * ) ; void xstrcpy ( char *, char * ) ; void xstrcat ( char *, char * ) ; int xstrcmp ( char *, char * ) ; void show ( char * ) ; void main( ) { char s1[ ] = "kicit" ; char s2[ ] = "Nagpur" ; char s3[20] ; int len ; clrscr( ) ; printf ( "\nString s1: %s", s1 ) ; len = xstrlen ( s1 ) ; printf ( "\nlength of the string s1: %d", len ) ; printf ( "\nString s2: %s", s2 ) ; xstrcpy ( s3, s1 ) ; printf ( "\nString s3 after copying s1 to it: %s", s3 ) ; xstrcat ( s3, s2 ) ;

printf ( "\nString s3 after concatenation: %s", s3 ) ; if ( xstrcmp ( s1, s2 ) == 0 ) printf ( "\nThe strings s1 and s2 are similar" ) ; else printf ( "\nThe strings s1 and s2 are not similar" ) ; getch( ) ; } /* finds the length of the string */ int xstrlen ( char *s ) { int l = 0 ; while ( *s ) { l++ ; s++ ; } return l ; } /* copies source string s to the target string t */ void xstrcpy ( char *t, char *s ) { while ( *s ) { *t = *s ; t++ ; s++ ; } *t = '\0' ; } /* concatenates the two strings */ void xstrcat ( char *t, char *s ) { while ( *t ) t++ ; while ( *s ) *t++ = *s++ ; *t = '\0' ; } /* compares two strings s and t for equality */ int xstrcmp ( char *s, char *t )

{ while ( *s == *t ) { if ( ! ( *s ) ) return 0 ; s++ ; t++ ; } return ( *s - *t ) ; } /* CH3PR2: Program to check entered name in the master list. */ #include <stdio.h> #include <conio.h> #include <string.h> #define MAX1 6 #define MAX2 10 char masterlist[MAX1][MAX2] ; int count ; int add ( char *s ) ; int find ( char *s ) ; void main( ) { char yourname[MAX2] ; int flag ; clrscr( ) ; flag = add ( "akshay" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "parag" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "raman" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "srinivas" ) ; if ( flag == 0 )

printf ( "\nUnable to add string" ) ; flag = add ( "gopal" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "rajesh" ) ; if ( flag == 0 ) printf ( "Unable to add string" ) ; printf ( "Enter your name: " ) ; gets ( yourname ) ; flag = find ( yourname ) ; if ( flag == 1 ) printf ( "Welcome, you can enter the palace\n" ) ; else printf ( "Sorry, you are a trespasser" ) ; getch( ) ; } /* adds string to the array */ int add ( char *s ) { if ( count < MAX1 ) { if ( strlen ( s ) < MAX2 ) { strcpy ( &masterlist[count][0], s ) ; count++ ; return 1 ; } } return 0 ; } /* finds the given string */ int find ( char *s ) { int flag = 0, i ; for ( i = 0 ; i < count ; i++ ) { if ( strcmp ( &masterlist[i][0], s ) == 0 ) {

flag = 1 ; break ; } } return flag ; } /* CH3PR2: Program to check entered name in the master list. */ #include <stdio.h> #include <conio.h> #include <string.h> #define MAX1 6 #define MAX2 10 char masterlist[MAX1][MAX2] ; int count ; int add ( char *s ) ; int find ( char *s ) ; void main( ) { char yourname[MAX2] ; int flag ; clrscr( ) ; flag = add ( "akshay" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "parag" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "raman" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "srinivas" ) ; if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "gopal" ) ;

if ( flag == 0 ) printf ( "\nUnable to add string" ) ; flag = add ( "rajesh" ) ; if ( flag == 0 ) printf ( "Unable to add string" ) ; printf ( "Enter your name: " ) ; gets ( yourname ) ; flag = find ( yourname ) ; if ( flag == 1 ) printf ( "Welcome, you can enter the palace\n" ) ; else printf ( "Sorry, you are a trespasser" ) ; getch( ) ; } /* adds string to the array */ int add ( char *s ) { if ( count < MAX1 ) { if ( strlen ( s ) < MAX2 ) { strcpy ( &masterlist[count][0], s ) ; count++ ; return 1 ; } } return 0 ; } /* finds the given string */ int find ( char *s ) { int flag = 0, i ; for ( i = 0 ; i < count ; i++ ) { if ( strcmp ( &masterlist[i][0], s ) == 0 ) { flag = 1 ; break ; }

} return flag ; } /* CH3PR4.C: Program to allocate memory dynamically for strings, and store their addresses in array of pointers to strings. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #include <string.h> void main( ) { char *name[5] ; char str[20] ; int i ; clrscr( ) ; for ( i = 0 ; i < 5 ; i++ ) { printf ( "Enter a String: " ) ; gets ( str ) ; name[i] = ( char * ) malloc ( strlen ( str ) + 1 ) ; strcpy ( name[i], str ) ; } printf ( "\nThe strings are:" ) ; for ( i = 0 ; i < 5 ; i++ ) printf ( "\n%s", name[i] ) ; for ( i = 0 ; i < 5 ; i++ ) free ( name[i] ) ; getch( ) ; } /* CH3PR5.C: Program to search for a string into another string. */ #include <stdio.h> #include <conio.h> #include <string.h> int xstrsearch ( char *, char * ) ;

void show( ) ; void main( ) { char s1[ ] = "NagpurKicit" ; char s2[ ] = "Kicit" ; int pos ; clrscr( ) ; printf ( "String s1: %s\n", s1 ) ; printf ( "String s2: %s\n", s2 ) ; /* search if s2 is present in s1 */ pos = xstrsearch ( s1, s2 ) ; printf ( "\nThe pattern string is found at position: %d\n", pos ) ; getch( ) ; } /* searches for the given pattern s2 into the string s1 */ int xstrsearch ( char * s1, char * s2 ) { int i, j, k ; int l1 = strlen ( s1 ) ; int l2 = strlen ( s2 ) ; for ( i = 0 ; i <= l1 - l2 ; i++ ) { j=0; k=i; while ( ( s1[k] == s2[j] ) && ( j < l2 ) ) { k++ ; j++ ; } if ( j == l2 ) return i ; } return -1 ; } /* CH3PR6.C: Few more string functions. */ #include <stdio.h>

#include <conio.h> #include <string.h> #include <alloc.h> int search ( char *, char ) ; int isequals ( char *, char * ) ; int issmaller ( char *, char * ) ; int isgreater ( char *, char * ) ; char * getsub ( char *, int, int ) ; char * leftsub ( char *, int n ) ; char * rightsub ( char *, int n ) ; void upper ( char * ) ; void lower ( char * ) ; void reverse ( char * ) ; int replace ( char *, char, char ) ; int setat ( char *, char, int ) ; void main( ) { char s1[ ] = "Hello" ; char s2[ ] = "Hello World" ; char s3[ ] = "Four hundred thirty two" ; char ch, *s ; int i ; clrscr( ) ; printf ( "\nString s1: %s", s1 ) ; /* check for the first occurrence of a character */ printf ( "\nEnter character to search: " ) ; scanf ( "%c", &ch ) ; i = search ( s1, ch ) ; if ( i != -1 ) printf ( "The first occurrence of character %c is found at index no. %d\n", ch, i ) ; else printf ( "Character %c is not present in the list.\n", ch ) ; printf ( "\nString s2: %s", s2 ) ; /* compares two strings s1 and s2 */ i = isequals ( s1, s2 ) ; if ( i == 1 ) printf ( "\nStrings s1 and s2 are identical" ) ; else

printf ( "\nStrings s1 and s2 are not identical") ; i = issmaller ( s1, s2 ) ; if ( i == 1 ) printf ( "\nString s1 is smaller than string s2" ) ; else printf ( "\nString s1 is not smaller than string s2" ) ; i = isgreater ( s1, s2 ) ; if ( i == 1 ) printf ( "\nString s1 is greater than string s2\n" ) ; else printf ( "\nString s1 is not greater than string s2\n" ) ; /* extract characters at given position */ printf ( "\nString s3: %s", s3 ) ; s = getsub ( s3, 5, 7 ) ; printf ( "\nSub string: %s", s ) ; free ( s ) ; /* extract leftmost n characters */ s = leftsub ( s3, 4 ) ; printf ( "\nLeft sub string: %s", s ) ; free ( s ) ; /* extract rightmost n characters */ s = rightsub ( s3, 3 ) ; printf ( "\nRight sub string: %s", s ) ; free ( s ) ; /* convert string to uppercase */ upper ( s3 ) ; printf ( "\nString in upper case: %s", s3 ) ; /* convert string to lowercase */ lower ( s3 ) ; printf ( "\nString in lower case: %s", s3 ) ; /* reverse the given string */ reverse ( s3 ) ; printf ( "\nReversed string: %s", s3 ) ; /* replace first occurrence of one char with new one */ replace ( s1, 'H' , 'M' ) ; printf ( "\nString s1: %s", s1 ) ; /* sets a char at a given position */

i = setat ( s1, 'M', 3 ) ; if ( i ) printf ( "\nString s1: %s", s1 ) ; else printf ( "\nInvalid position." ) ; getch( ) ; } /* check for the first occurrence of a character */ int search ( char *str, char ch ) { int i = 0 ; while ( *str ) { if ( *str == ch ) return i ; str++ ; i++ ; } return -1 ; } /* checks whether two strings are equal */ int isequals ( char *s, char *t ) { while ( *s || *t ) { if ( *s != *t ) return 0 ; s++ ; t++ ; } return 1 ; } /* checks whether first string is less than second */ int issmaller ( char *s, char *t ) { while ( *t ) { if ( *s != *t ) { if ( *s < *t ) return 1 ;

else return 0 ; } t++ ; s++ ; } return 0 ; } /* checks whether first string is greater than second */ int isgreater ( char *s, char *t ) { while ( *s ) { if ( *s != *t ) { if ( *s > *t ) return 1 ; else return 0 ; } s++ ; t++ ; } return 0 ; } /* extracts the character at given position */ char * getsub ( char *str, int spos, int n ) { char *s = str + spos ; char *t = ( char * ) malloc ( n + 1 ) ; int i = 0 ; while ( i < n ) { t[i] = *s ; s++ ; i++ ; } t[i] = '\0' ; return t ; } /* extracts leftmost n characters from the string */

char * leftsub ( char *s, int n ) { char *t = ( char * ) malloc ( n + 1 ) ; int i = 0 ; while ( i < n ) { t[i] = *s ; s++ ; i++ ; } t[i] = '\0' ; return t ; } /* extracts rightmost n characters from the string */ char * rightsub ( char *str, int n ) { char *t = ( char * ) malloc ( n + 1 ) ; int l = strlen ( str ) ; char *s = str + ( l - n ) ; int i = 0 ; while ( i < n ) { t[i] = *s ; s++ ; i++ ; } t[i] = '\0' ; return t ; } /* converts string to uppercase */ void upper ( char *s ) { while ( *s ) { if ( *s >= 97 && *s <= 123 ) *s -= 32 ; s++ ; } } /* converts string to lowercase */

void lower ( char *s ) { while ( *s ) { if ( *s >= 65 && *s <= 91 ) *s += 32 ; s++ ; } } /* reverses a string */ void reverse ( char *str ) { int l = strlen ( str ) ; char ch, *t = ( str + l - 1 ) ; int i = 0 ; while ( i < l / 2 ) { ch = *str ; *str = *t ; *t = ch ; str++ ; t-- ; i++ ; } } /* replaces the first occurrence of char with new char */ int replace ( char *str, char oldch, char newch ) { while ( *str ) { if ( *str == oldch ) { *str = newch ; return 1 ; } str++ ; } return 0 ; } /* sets a char at a given position */ int setat ( char *str, char ch, int i )

{ if ( i < 0 || strlen ( str ) < i ) return 0 ; * ( str + i ) = ch ; return 1 ; } /* CH4PR1.C: Program to maintain a linked list */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node * link ; }; void append ( struct node **, int ) ; void addatbeg ( struct node **, int ) ; void addafter ( struct node *, int, int ) ; void display ( struct node * ) ; int count ( struct node * ) ; void delete ( struct node **, int ) ; void main( ) { struct node *p ; p = NULL ; /* empty linked list */ printf ( "\nNo. of elements in the Linked List = %d", count ( p ) ) ; append ( &p, 14 ) ; append ( &p, 30 ) ; append ( &p, 25 ) ; append ( &p, 42 ) ; append ( &p, 17 ) ; display ( p ) ; addatbeg ( &p, 999 ) ; addatbeg ( &p, 888 ) ; addatbeg ( &p, 777 ) ; display ( p ) ;

addafter ( p, 7, 0 ) ; addafter ( p, 2, 1 ) ; addafter ( p, 5, 99 ) ; display ( p ) ; printf ( "\nNo. of elements in the Linked List = %d", count ( p ) ) ; delete ( &p, 99 ) ; delete ( &p, 1 ) ; delete ( &p, 10 ) ; display ( p ) ; printf ( "\nNo. of elements in the Linked List = %d", count ( p ) ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp, *r ; if ( *q == NULL ) /* if the list is empty, create first node */ { temp = malloc ( sizeof ( struct node ) ) ; temp -> data = num ; temp -> link = NULL ; *q = temp ; } else { temp = *q ; /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; r -> link = NULL ; temp -> link = r ; } } /* adds a new node at the beginning of the linked list */ void addatbeg ( struct node **q, int num )

{ struct node *temp ; /* add new node */ temp = malloc ( sizeof ( struct node ) ) ; temp -> data = num ; temp -> link = *q ; *q = temp ; } /* adds a new node after the specified number of nodes */ void addafter ( struct node *q, int loc, int num ) { struct node *temp, *r ; int i ; temp = q ; /* skip to desired portion */ for ( i = 0 ; i < loc ; i++ ) { temp = temp -> link ; /* if end of linked list is encountered */ if ( temp == NULL ) { printf ( "\nThere are less than %d elements in list", loc ) ; return ; } } /* insert new node */ r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; r -> link = temp -> link ; temp -> link = r ; } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) {

printf ( "%d ", q -> data ) ; q = q -> link ; } } /* counts the number of nodes present in the linked list */ int count ( struct node * q ) { int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> link ; c++ ; } return c ; } /* deletes the specified node from the linked list */ void delete ( struct node **q, int num ) { struct node *old, *temp ; temp = *q ; while ( temp != NULL ) { if ( temp -> data == num ) { /* if node to be deleted is the first node in the linked list */ if ( temp == *q ) *q = temp -> link ; /* deletes the intermediate nodes in the linked list */ else old -> link = temp -> link ; /* free the memory occupied by the node */ free ( temp ) ; return ; } /* traverse the linked list till the last node is reached */ else

{ old = temp ; /* old points to the previous node */ temp = temp -> link ; /* go to the next node */ } } printf ( "\nElement %d not found", num ) ; } /* CH4PR2.C: Program to add a new node to the asscending order linked list. */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void add ( struct node **, int ) ; void display ( struct node * ) ; int count ( struct node * ) ; void delete ( struct node **, int ) ; void main( ) { struct node *p ; p = NULL ; /* empty linked list */ add ( &p, 5 ) ; add ( &p, 1 ) ; add ( &p, 6 ) ; add ( &p, 4 ) ; add ( &p, 7 ) ; clrscr( ) ; display ( p ) ; printf ( "\nNo. of elements in Linked List = %d", count ( p ) ) ; } /* adds node to an ascending order linked list */ void add ( struct node **q, int num ) {

struct node *r, *temp = *q ; r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; /* if list is empty or if new node is to be inserted before the first node */ if ( *q == NULL || ( *q ) -> data > num ) { *q = r ; ( *q ) -> link = temp ; } else { /* traverse the entire linked list to search the position to insert the new node */ while ( temp != NULL ) { if ( temp -> data <= num && ( temp -> link -> data > num || temp -> link == NULL )) { r -> link = temp -> link ; temp -> link = r ; return ; } temp = temp -> link ; /* go to the next node */ } } } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf ( "%d ", q -> data ) ; q = q -> link ; } } /* counts the number of nodes present in the linked list */ int count ( struct node *q ) {

int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> link ; c++ ; } return c ; } /* CH4PR3.C: Program to reverse a linked list */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void addatbeg ( struct node **, int ) ; void reverse ( struct node ** ) ; void display ( struct node * ) ; int count ( struct node * ) ; void main( ) { struct node *p ; p = NULL ; /* empty linked list */ addatbeg ( &p, 7 ) ; addatbeg ( &p, 43 ) ; addatbeg ( &p, 17 ) ; addatbeg ( &p, 3 ) ; addatbeg ( &p, 23 ) ; addatbeg ( &p, 5 ) ; clrscr( ) ; display ( p ) ; printf ( "\nNo. of elements in the linked list = %d", count ( p ) ) ; reverse ( &p ) ;

display ( p ) ; printf ( "\nNo. of elements in the linked list = %d", count ( p ) ) ; } /* adds a new node at the beginning of the linked list */ void addatbeg ( struct node **q, int num ) { struct node *temp ; /* add new node */ temp = malloc ( sizeof ( struct node ) ) ; temp -> data = num ; temp -> link = *q ; *q = temp ; } void reverse ( struct node **x ) { struct node *q, *r, *s ; q = *x ; r = NULL ; /* traverse the entire linked list */ while ( q != NULL ) { s=r; r=q; q = q -> link ; r -> link = s ; } *x = r ; } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf ( "%d ", q -> data ) ; q = q -> link ; }

} /* counts the number of nodes present in the linked list */ int count ( struct node * q ) { int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> link ; c++ ; } return c ; } /* CH4PR4.C: Program to merge two linked list, restricting commomn elements to occur only once */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void add ( struct node **, int ) ; void display ( struct node * ) ; int count ( struct node * ) ; void merge ( struct node *, struct node *, struct node ** ) ; void main( ) { struct node *first, *second, *third ; first = second = third = NULL ; /* empty linked lists */ add ( &first, 9 ) ; add ( &first, 12 ) ; add ( &first, 14 ) ; add ( &first, 17 ) ; add ( &first, 35 ) ; add ( &first, 61 ) ;

add ( &first, 79 ) ; clrscr( ) ; printf ( "First linked list : " ) ; display ( first ) ; printf ( "\nNo. of elements in Linked List : %d" , count ( first ) ) ; add ( &second, 12 ) ; add ( &second, 17 ) ; add ( &second, 24 ) ; add ( &second, 36 ) ; add ( &second, 59 ) ; add ( &second, 64 ) ; add ( &second, 87 ) ; printf ( "\n\nSecond linked list : " ) ; display ( second ) ; printf ( "\nNo. of elements in Linked List : %d" , count ( second ) ) ; merge ( first, second, &third ) ; printf ( "\n\nThe merged list : " ) ; display ( third ) ; printf ( "\nNo. of elements in Linked List : %d", count ( third ) ) ; } /* adds node to an ascending order linked list */ void add ( struct node **q, int num ) { struct node *r, *temp = *q ; r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; /* if list is empty or if new node is to be inserted before the first node */ if ( *q == NULL || ( *q ) -> data > num ) { *q = r ; ( *q ) -> link = temp ; } else { /* traverse the entire linked list to search the position to insert the new node */ while ( temp != NULL ) {

if ( temp -> data < num && ( temp -> link -> data > num || temp -> link == NULL )) { r -> link = temp -> link ; temp -> link = r ; return ; } temp = temp -> link ; /*go to next node */ } r -> link = NULL ; temp -> link = r ; } } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf ( "%d ", q -> data ) ; q = q -> link ; } } /* counts the number of nodes present in the linked list */ int count ( struct node * q ) { int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> link ; c++ ; } return c ; } /* merges the two linked lists, restricting the common elements to occur only once in the final list */ void merge ( struct node *p, struct node *q, struct node **s )

{ struct node *z ; z = NULL ; /* if both lists are empty */ if ( p == NULL && q == NULL ) return ; /* traverse both linked lists till the end. If end of any one list is reached loop is terminated */ while ( p != NULL && q != NULL ) { /* if node being added in the first node */ if ( *s == NULL ) { *s = malloc ( sizeof ( struct node ) ) ; z = *s ; } else { z -> link = malloc ( sizeof ( struct node ) ) ; z = z -> link ; } if ( p -> data < q -> data ) { z -> data = p -> data ; p = p -> link ; } else { if ( q -> data < p -> data ) { z -> data = q -> data ; q = q -> link ; } else { if ( p -> data == q -> data ) { z -> data = q -> data ; p = p -> link ; q = q -> link ; } }

} } /* if end of first list has not been reached */ while ( p != NULL ) { z -> link = malloc ( sizeof ( struct node ) ) ; z = z -> link ; z -> data = p -> data ; p = p -> link ; } /* if end of second list has been reached */ while ( q != NULL ) { z -> link = malloc ( sizeof ( struct node ) ) ; z = z -> link ; z -> data = q -> data ; q = q -> link ; } z -> link = NULL ; } /* CH4PR5.C: Program to sort a linked list by swapping data.*/ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; } *newnode, *start, *visit ; void getdata( ) ; void append ( struct node **, int ) ; void displaylist( ) ; int count ( struct node * ) ; void selection_sort ( int ) ; void bubble_sort ( int ) ; void main( ) { int n ;

getdata( ) ; clrscr( ) ; printf ( "Linked List Before Sorting: " ) ; displaylist( ) ; n = count ( start ) ; selection_sort ( n ) ; printf ( "\nLinked List After Selection Sorting: " ) ; displaylist( ) ; getch( ) ; getdata( ) ; clrscr( ) ; printf ( "Linked List Before Sorting: " ) ; displaylist( ) ; n = count ( start ) ; bubble_sort ( n ) ; printf ( "\nLinked List After Bubble Sorting: " ) ; displaylist( ) ; getch( ) ; } void getdata( ) { int val, n ; char ch ; struct node *new ; clrscr( ) ; new = NULL ; do { printf ( "\nEnter a value: " ) ; scanf ( "%d", &val ) ; append ( &new, val ) ; printf ( "\nAny More Nodes (Y/N): " ) ; ch = getche( ) ; } while ( ch == 'y' || ch == 'Y' ) ;

start = new ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; } else { /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ; } /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* displays the contents of the linked list */ void displaylist( ) { visit = start ; /* traverse the entire linked list */ while ( visit != NULL ) { printf ( "%d ", visit -> data ) ; visit = visit -> link ; } } /* counts the number of nodes present in the linked list */ int count ( struct node * q )

{ int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> link ; c++ ; } return c ; } void selection_sort ( int n ) { int i, j, k, temp ; struct node *p, *q ; p = start ; for ( i = 0 ; i < n - 1 ; i++ ) { q = p -> link ; for ( j = i + 1 ; j < n ; j++ ) { if ( p -> data > q -> data ) { temp = p -> data ; p -> data = q -> data ; q -> data = temp ; } q = q -> link ; } p = p -> link ; } } void bubble_sort ( int n ) { int i, j, k, temp ; struct node *p, *q ; k=n; for ( i = 0 ; i < n - 1 ; i++, k-- ) { p = start ;

q = p -> link ; for ( j = 1 ; j < k ; j++ ) { if ( p -> data > q -> data ) { temp = p -> data ; p -> data = q -> data ; q -> data = temp ; } p = p -> link ; q = q -> link ; } } } /* CH4PR6.C: Program to sort a linked list by readjusting the links. */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; } *start, *visit ; void getdata( ) ; void append ( struct node **q, int num ) ; void displaylist( ) ; void selection_sort( ) ; void bubble_sort( ) ; void main( ) { getdata( ) ; clrscr( ) ; printf ( "\nLinked List Before Sorting:\n" ) ; displaylist( ) ; selection_sort( ) ; printf ( "\nLinked List After Selection Sorting:\n" ) ; displaylist( ) ; getch( ) ;

getdata( ) ; clrscr( ) ; printf ( "\nLinked List Before Sorting:\n" ) ; displaylist( ) ; bubble_sort( ) ; printf ( "\nLinked List After Bubble Sorting:\n" ) ; displaylist( ) ; getch( ) ; } void getdata( ) { int val, n ; char ch ; struct node *newnode; clrscr( ) ; newnode = NULL ; do { printf ( "\nEnter a value: " ) ; scanf ( "%d", &val ) ; append ( &newnode, val ) ; printf ( "\nAny More Nodes (Y/N): " ) ; ch = getche( ) ; } while ( ch == 'y' || ch == 'Y' ) ; start = newnode ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; }

else { /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ; } /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* displays the contents of the linked list */ void displaylist( ) { visit = start ; /* traverse the entire linked list */ while ( visit != NULL ) { printf ( "%d ", visit -> data ) ; visit = visit -> link ; } } void selection_sort( ) { struct node *p, *q, *r, *s, *temp ; p = r = start ; while ( p -> link != NULL ) { s = q = p -> link ; while ( q != NULL ) { if ( p -> data > q -> data ) { if ( p -> link == q ) /* Adjacent Nodes */ { if ( p == start ) { p -> link = q -> link ;

q -> link = p ; temp = p ; p=q; q = temp ; start = p ; r=p; s=q; q = q -> link ; } else { p -> link = q -> link ; q -> link = p ; r -> link = q ; temp = p ; p=q; q = temp ; s=q; q = q -> link ; } } else { if ( p == start ) { temp = q -> link ; q -> link = p -> link ; p -> link = temp ; s -> link = p ; temp = p ; p=q; q = temp ; s=q; q = q -> link ; start = p ; } else { temp = q -> link ;

q -> link = p -> link ; p -> link = temp ; r -> link = q ; s -> link = p ; temp = p ; p=q; q = temp ; s=q; q = q -> link ; } } } else { s=q; q = q -> link ; } } r=p; p = p -> link ; } } void bubble_sort( ) { struct node *p, *q, *r, *s, *temp ; s = NULL ; /* r precedes p and s points to the node up to which comparisons are to be made */ while ( s != start -> link ) { r = p = start ; q = p -> link ; while ( p != s ) { if ( p -> data > q -> data ) { if ( p == start ) { temp = q -> link ; q -> link = p ; p -> link = temp ;

start = q ; r=q; } else { temp = q -> link ; q -> link = p ; p -> link = temp ; r -> link = q ; r=q; } } else { r=p; p = p -> link ; } q = p -> link ; if ( q == s ) s=p; } } } /* CH4PR7.C: Program to implement a circular queue as a linked list. */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node * link ; }; void addcirq ( struct node **, struct node **, int ) ; int delcirq ( struct node **, struct node ** ) ; void cirq_display ( struct node * ) ; void main( ) { struct node *front, *rear ;

front = rear = NULL ; addcirq ( &front, &rear, 10 ) ; addcirq ( &front, &rear, 17 ) ; addcirq ( &front, &rear, 18 ) ; addcirq ( &front, &rear, 5 ) ; addcirq ( &front, &rear, 30 ) ; addcirq ( &front, &rear, 15 ) ; clrscr( ) ; printf ( "Before deletion:\n" ) ; cirq_display ( front ) ; delcirq ( &front, &rear ) ; delcirq ( &front, &rear ) ; delcirq ( &front, &rear ) ; printf ( "\n\nAfter deletion:\n" ) ; cirq_display ( front ) ; } /* adds a new element at the end of queue */ void addcirq ( struct node **f, struct node **r, int item ) { struct node *q ; /* create new node */ q = malloc ( sizeof ( struct node ) ) ; q -> data = item ; /* if the queue is empty */ if ( *f == NULL ) *f = q ; else ( *r ) -> link = q ; *r = q ; ( *r ) -> link = *f ; } /* removes an element from front of queue */ int delcirq ( struct node **f, struct node **r ) { struct node *q ;

int item ; /* if queue is empty */ if ( *f == NULL ) printf ( "queue is empty" ) ; else { if ( *f == *r ) { item = ( *f ) -> data ; free ( *f ) ; *f = NULL ; *r = NULL ; } else { /* delete the node */ q = *f ; item = q -> data ; *f = ( *f ) -> link ; ( *r ) -> link = *f ; free ( q ) ; } return ( item ) ; } return NULL ; } /* displays whole of the queue */ void cirq_display ( struct node *f ) { struct node *q = f, *p = NULL ; /* traverse the entire linked list */ while ( q != p ) { printf ( "%d\t", q -> data ) ; q = q -> link ; p=f; } }/* CH4PR8.C: Program to concatenate one linked list at end of another and than to erase all nodes present in the linked list */ #include <stdio.h> #include <conio.h>

#include <alloc.h> struct node { int data ; struct node *link ; }; void append ( struct node **, int ) ; void concat ( struct node **, struct node ** ) ; void display ( struct node * ) ; int count ( struct node * ) ; struct node * erase ( struct node * ) ; void main( ) { struct node *first, *second ; first = second = NULL ; /* empty linked lists */ append ( &first, 1 ) ; append ( &first, 2 ) ; append ( &first, 3 ) ; append ( &first, 4 ) ; clrscr( ) ; printf ( "\nFirst List : " ) ; display ( first ) ; printf ( "\nNo. of elements in the first Linked List = %d", count ( first ) ) ; append ( &second, 5 ) ; append ( &second, 6 ) ; append ( &second, 7 ) ; append ( &second, 8 ) ; printf ( "\n\nSecond List : " ) ; display ( second ) ; printf ( "\nNo. of elements in the second Linked List = %d", count ( second ) ) ; /* the result obtained after concatenation is in the first list */ concat ( &first, &second ) ; printf ( "\n\nConcatenated List : " ) ; display ( first ) ;

printf ( "\n\nNo. of elements in Linked List before erasing = %d", count ( first ) ) ; first = erase ( first ) ; printf ( "\nNo. of elements in Linked List after erasing = %d", count ( first ) ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; } else { /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ; } /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* concatenates two linked lists */ void concat ( struct node **p, struct node **q ) { struct node *temp ; /* if the first linked list is empty */ if ( *p == NULL ) *p = *q ; else {

/* if both linked lists are non-empty */ if ( *q != NULL ) { temp = *p ; /* points to the starting of the first list */ /* traverse the entire first linked list */ while ( temp -> link != NULL ) temp = temp -> link ; temp -> link = *q ; /* concatenate the second list after the first */ } } } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf ( "%d ", q -> data ) ; q = q -> link ; } } /* counts the number of nodes present in the linked list */ int count ( struct node *q ) { int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> link ; c++ ; } return c ; } /* erases all the nodes from a linked list */ struct node * erase ( struct node *q ) {

struct node *temp ; /* traverse till the end erasing each node */ while ( q != NULL ) { temp = q ; q = q -> link ; free ( temp ) ; /* free the memory occupied by the node */ } return NULL ; }

/* CH4PR9.C: Program to find the number of nodes in the linked list using recursion */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void append ( struct node **, int ) ; int length ( struct node * ) ; void main( ) { struct node *p ; p = NULL ; /* empty linked list */ append ( &p, 1 ) ; append ( &p, 2 ) ; append ( &p, 3 ) ; append ( &p, 4 ) ; append ( &p, 5 ) ; clrscr( ) ; printf ( "Length of linked list = %d", length ( p ) ) ; }

/* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; } else { /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ; } /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* counts the number of nodes in a linked list */ int length ( struct node *q ) { static int l ; /* if list is empty or if NULL is encountered */ if ( q == NULL ) return ( 0 ) ; else { /* go to next node */ l = 1 + length ( q -> link ) ; return ( l ) ; } } /* CH4PR10.C: Program to compare two linked lists using recursion */ #include <stdio.h>

#include <conio.h> #include <alloc.h> struct node { int data ; struct node *link ; }; void append ( struct node **, int ) ; int compare ( struct node *, struct node * ) ; void main( ) { struct node *first, *second ; first = second = NULL ; /* empty linked lists */ append ( &first, 1 ) ; append ( &first, 2 ) ; append ( &first, 3 ) ; append ( &second, 1 ) ; append ( &second, 2 ) ; append ( &second, 3 ) ; clrscr( ) ; if ( compare ( first, second ) ) printf ( "Both linked lists are EQUAL" ) ; else printf ( "Linked lists are DIFFERENT" ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; } else { /* go to last node */

while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ; } /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* compares 2 linked lists and returns 1 if linked lists are equal and 0 if unequal */ int compare ( struct node *q, struct node *r ) { static int flag ; if ( ( q == NULL ) && ( r == NULL ) ) flag = 1 ; else { if ( q == NULL || r == NULL ) flag = 0 ; if ( q -> data != r -> data ) flag = 0 ; else compare ( q -> link, r -> link ) ; } return ( flag ) ; } /* CH4PR11.C: Program to copy one linked list into another using recursion */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; };

void append ( struct node **, int ) ; void copy ( struct node *, struct node ** ) ; void display ( struct node * ) ; void main( ) { struct node *first, *second ; first = second = NULL ; /* empty linked lists */ append ( &first, 1 ) ; append ( &first, 2 ) ; append ( &first, 3 ) ; append ( &first, 4 ) ; append ( &first, 5 ) ; append ( &first, 6 ) ; append ( &first, 7 ) ; clrscr( ) ; display ( first ) ; copy ( first, &second ) ; display ( second ) ; } /* adds a node at the end of the linked list */ void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; } else { /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ;

} /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* copies a linked list into another */ void copy ( struct node *q, struct node **s ) { if ( q != NULL ) { *s = malloc ( sizeof ( struct node ) ) ; ( *s ) -> data = q -> data ; ( *s ) -> link = NULL ; copy ( q -> link, &( ( *s ) -> link ) ) ; } } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf ( "%d ", q -> data ) ; q = q -> link ; } } /* CH4PR12.C: Program to add a new node at the end of linked list using recursion*/ #include <stdio.h> #include <conio.h> #include <alloc.h> struct node { int data ; struct node *link ; };

void addatend ( struct node **, int ) ; void display ( struct node * ) ; void main( ) { struct node *p ; p = NULL ; addatend ( &p, 1 ) ; addatend ( &p, 2 ) ; addatend ( &p, 3 ) ; addatend ( &p, 4 ) ; addatend ( &p, 5 ) ; addatend ( &p, 6 ) ; addatend ( &p, 10 ) ; clrscr( ) ; display ( p ) ; } /* adds a new node at the end of the linked list */ void addatend ( struct node **s, int num ) { if ( *s == NULL ) { *s = malloc ( sizeof ( struct node ) ) ; ( *s ) -> data = num ; ( *s ) -> link = NULL ; } else addatend ( &( ( *s ) -> link ), num ) ; } /* displays the contents of the linked list */ void display ( struct node *q ) { printf ( "\n" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf ( "%d ", q -> data ) ; q = q -> link ; } }

/* CH4PR13.C: Program to maintain a doubly linked list */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure representing a node of the doubly linked list */ struct dnode { struct dnode *prev ; int data ; struct dnode * next ; }; void d_append ( struct dnode **, int ) ; void d_addatbeg ( struct dnode **, int ) ; void d_addafter ( struct dnode *, int , int ) ; void d_display ( struct dnode * ) ; int d_count ( struct dnode * ) ; void d_delete ( struct dnode **, int ) ; void main( ) { struct dnode *p ; p = NULL ; /* empty doubly linked list */ d_append ( &p , 11 ) ; d_append ( &p , 2 ) ; d_append ( &p , 14 ) ; d_append ( &p , 17 ) ; d_append ( &p , 99 ) ; clrscr( ) ; d_display ( p ) ; printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ; d_addatbeg ( &p, 33 ) ; d_addatbeg ( &p, 55 ) ; d_display ( p ) ; printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ; d_addafter ( p, 4, 66 ) ; d_addafter ( p, 2, 96 ) ;

d_display ( p ) ; printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ; d_delete ( &p, 55 ) ; d_delete ( &p, 2 ) ; d_delete ( &p, 99 ) ; d_display ( p ) ; printf ( "\nNo. of elements in the DLL = %d\n", d_count ( p ) ) ; } /* adds a new node at the end of the doubly linked list */ void d_append ( struct dnode **s, int num ) { struct dnode *r, *q = *s ; /* if the linked list is empty */ if ( *s == NULL ) { /*create a new node */ *s = malloc ( sizeof ( struct dnode ) ) ; ( *s ) -> prev = NULL ; ( *s ) -> data = num ; ( *s ) -> next = NULL ; } else { /* traverse the linked list till the last node is reached */ while ( q -> next != NULL ) q = q -> next ; /* add a new node at the end */ r = malloc ( sizeof ( struct dnode ) ) ; r -> data = num ; r -> next = NULL ; r -> prev = q ; q -> next = r ; } } /* adds a new node at the begining of the linked list */ void d_addatbeg ( struct dnode **s, int num ) { struct dnode *q ;

/* create a new node */ q = malloc ( sizeof ( struct dnode ) ) ; /* assign data and pointer to the new node */ q -> prev = NULL ; q -> data = num ; q -> next = *s ; /* make new node the head node */ ( *s ) -> prev = q ; *s = q ; } /* adds a new node after the specified number of nodes */ void d_addafter ( struct dnode *q, int loc, int num ) { struct dnode *temp ; int i ; /* skip to desired portion */ for ( i = 0 ; i < loc ; i++ ) { q = q -> next ; /* if end of linked list is encountered */ if ( q == NULL ) { printf ( "\nThere are less than %d elements", loc ); return ; } } /* insert new node */ q = q -> prev ; temp = malloc ( sizeof ( struct dnode ) ) ; temp -> data = num ; temp -> prev = q ; temp -> next = q -> next ; temp -> next -> prev = temp ; q -> next = temp ; } /* displays the contents of the linked list */ void d_display ( struct dnode *q ) { printf ( "\n" ) ;

/* traverse the entire linked list */ while ( q != NULL ) { printf ( "%2d\t", q -> data ) ; q = q -> next ; } } /* counts the number of nodes present in the linked list */ int d_count ( struct dnode * q ) { int c = 0 ; /* traverse the entire linked list */ while ( q != NULL ) { q = q -> next ; c++ ; } return c ; } /* deletes the specified node from the doubly linked list */ void d_delete ( struct dnode **s, int num ) { struct dnode *q = *s ; /* traverse the entire linked list */ while ( q != NULL ) { /* if node to be deleted is found */ if ( q -> data == num ) { /* if node to be deleted is the first node */ if ( q == *s ) { *s = ( *s ) -> next ; ( *s ) -> prev = NULL ; } else { /* if node to be deleted is the last node */ if ( q -> next == NULL ) q -> prev -> next = NULL ; else

/* if node to be deleted is any intermediate node */ { q -> prev -> next = q -> next ; q -> next -> prev = q -> prev ; } free ( q ) ; } return ; /* return back after deletion */ } q = q -> next ; /* go to next node */ } printf ( "\n%d not found.", num ) ; } /* CH4PR14.C: Program to add two polynomials maintained as linked lists. */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure representing a node of a linked list. The node can store term of a polynomial */ struct polynode { float coeff ; int exp ; struct polynode *link ; }; void poly_append ( struct polynode **, float, int ) ; void display_poly ( struct polynode * ) ; void poly_add ( struct polynode *, struct polynode *, struct polynode ** ) ; void main( ) { struct polynode *first, *second, *total ; int i = 0 ; first = second = total = NULL ; /* empty linked lists */ poly_append ( &first, 1.4, 5 ) ; poly_append ( &first, 1.5, 4 ) ; poly_append ( &first, 1.7, 2 ) ; poly_append ( &first, 1.8, 1 ) ; poly_append ( &first, 1.9, 0 ) ;

clrscr( ) ; display_poly ( first ) ; poly_append ( &second, 1.5, 6 ) ; poly_append ( &second, 2.5, 5 ) ; poly_append ( &second, -3.5, 4 ) ; poly_append ( &second, 4.5, 3 ) ; poly_append ( &second, 6.5, 1 ) ; printf ( "\n\n" ) ; display_poly ( second ) ; /* draws a dashed horizontal line */ printf ( "\n" ) ; while ( i++ < 79 ) printf ( "-" ) ; printf ( "\n\n" ) ; poly_add ( first, second, &total ) ; display_poly ( total ) ; /* displays the resultant polynomial */ } /* adds a term to a polynomial */ void poly_append ( struct polynode **q, float x, int y ) { struct polynode *temp ; temp = *q ; /* creates a new node if the list is empty */ if ( *q == NULL ) { *q = malloc ( sizeof ( struct polynode ) ) ; temp = *q ; } else { /* traverse the entire linked list */ while ( temp -> link != NULL ) temp = temp -> link ; /* create new nodes at intermediate stages */ temp -> link = malloc ( sizeof ( struct polynode ) ) ; temp = temp -> link ; } /* assign coefficient and exponent */

temp -> coeff = x ; temp -> exp = y ; temp -> link = NULL ; } /* displays the contents of linked list representing a polynomial */ void display_poly ( struct polynode *q ) { /* traverse till the end of the linked list */ while ( q != NULL ) { printf ( "%.1f x^%d : ", q -> coeff, q -> exp ) ; q = q -> link ; } printf ( "\b\b\b " ) ; /* erases the last colon */ } /* adds two polynomials */ void poly_add ( struct polynode *x, struct polynode *y, { struct polynode *z ; /* if both linked lists are empty */ if ( x == NULL && y == NULL ) return ; /* traverse till one of the list ends */ while ( x != NULL && y != NULL ) { /* create a new node if the list is empty */ if ( *s == NULL ) { *s = malloc ( sizeof ( struct polynode ) ) ; z = *s ; } /* create new nodes at intermediate stages */ else { z -> link = malloc ( sizeof ( struct polynode ) ) ; z = z -> link ; } /* store a term of the larger degree polynomial */ if ( x -> exp < y -> exp ) {

struct polynode **s )

z -> coeff = y -> coeff ; z -> exp = y -> exp ; y = y -> link ; /* go to the next node */ } else { if ( x -> exp > y -> exp ) { z -> coeff = x -> coeff ; z -> exp = x -> exp ; x = x -> link ; /* go to the next node */ } else { /* add the coefficients, when exponents are equal */ if ( x -> exp == y -> exp ) { /* assigning the added coefficient */ z -> coeff = x -> coeff + y -> coeff ; z -> exp = x -> exp ; /* go to the next node */ x = x -> link ; y = y -> link ; } } } } /* assign remaining terms of the first polynomial to the result */ while ( x != NULL ) { if ( *s == NULL ) { *s = malloc ( sizeof ( struct polynode ) ) ; z = *s ; } else { z -> link = malloc ( sizeof ( struct polynode ) ) ; z = z -> link ; } /* assign coefficient and exponent */ z -> coeff = x -> coeff ; z -> exp = x -> exp ; x = x -> link ; /* go to the next node */

} /* assign remaining terms of the second polynomial to the result */ while ( y != NULL ) { if ( *s == NULL ) { *s = malloc ( sizeof ( struct polynode ) ) ; z = *s ; } else { z -> link = malloc ( sizeof ( struct polynode ) ) ; z = z -> link ; } /* assign coefficient and exponent */ z -> coeff = y -> coeff ; z -> exp = y -> exp ; y = y -> link ; /* go to the next node */ } z -> link = NULL ; /* assign NULL at end of resulting linked list */ } /* CH4PR15.C: Program to multiply two polynomials maintained as linked lists.*/ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure representing a node of a linked list. The node can store a term of a polynomial */ struct polynode { float coeff ; int exp ; struct polynode *link ; }; void poly_append ( struct polynode **, float, int ) ; void display_poly ( struct polynode * ) ; void poly_multiply ( struct polynode *, struct polynode *, struct polynode ** ) ; void padd ( float, int, struct polynode ** ) ; void main( )

{ struct polynode *first, *second, *mult ; int i = 1 ; first = second = mult = NULL ; /* empty linked lists */ poly_append ( &first, 3, 5 ) ; poly_append ( &first, 2, 4 ) ; poly_append ( &first, 1, 2 ) ; clrscr( ) ; display_poly ( first ) ; poly_append ( &second, 1, 6 ) ; poly_append ( &second, 2, 5 ) ; poly_append ( &second, 3, 4 ) ; printf ( "\n\n" ) ; display_poly ( second ) ; printf ( "\n" ); while ( i++ < 79 ) printf ( "-" ) ; poly_multiply ( first, second, &mult ) ; printf ( "\n\n" ) ; display_poly ( mult ) ; } /* adds a term to a polynomial */ void poly_append ( struct polynode **q, float x, int y ) { struct polynode *temp ; temp = *q ; /* create a new node if the list is empty */ if ( *q == NULL ) { *q = malloc ( sizeof ( struct polynode ) ) ; temp = *q ; } else { /* traverse the entire linked list */ while ( temp -> link != NULL )

temp = temp -> link ; /* create new nodes at intermediate stages */ temp -> link = malloc ( sizeof ( struct polynode ) ) ; temp = temp -> link ; } /* assign coefficient and exponent */ temp -> coeff = x ; temp -> exp = y ; temp -> link = NULL ; } /* displays the contents of linked list representing a polynomial */ void display_poly ( struct polynode *q ) { /* traverse till the end of the linked list */ while ( q != NULL ) { printf ( "%.1f x^%d : ", q -> coeff, q -> exp ) ; q = q -> link ; } printf ( "\b\b\b " ) ; /* erases the last colon(:) */ } /* multiplies the two polynomials */ void poly_multiply ( struct polynode *x, struct polynode *y, struct polynode **m ) { struct polynode *y1 ; float coeff1, exp1 ; y1 = y ; /* point to the starting of the second linked list */ if ( x == NULL && y == NULL ) return ; /* if one of the list is empty */ if ( x == NULL ) *m = y ; else { if ( y == NULL ) *m = x ; else /* if both linked lists exist */

{ /* for each term of the first list */ while ( x != NULL ) { /* multiply each term of the second linked list with a term of the first linked list */ while ( y != NULL ) { coeff1 = x -> coeff * y -> coeff ; exp1 = x -> exp + y -> exp ; y = y -> link ; /* add the new term to the resultant polynomial */ padd ( coeff1, exp1, m ) ; } y = y1 ; /* reposition the pointer to the starting of the second linked list */ x = x -> link ; /* go to the next node */ } } } } /* adds a term to the polynomial in the descending order of the exponent */ void padd ( float c, int e, struct polynode **s ) { struct polynode *r, *temp = *s ; /* if list is empty or if the node is to be inserted before the first node */ if ( *s == NULL || e > ( *s ) -> exp ) { *s = r = malloc ( sizeof ( struct polynode ) ) ; ( *s ) -> coeff = c ; ( *s ) -> exp = e ; ( *s ) -> link = temp ; } else { /* traverse the entire linked list to search the position to insert a new node */ while ( temp != NULL ) { if ( temp -> exp == e ) {

temp -> coeff += c ; return ; } if ( temp -> exp > e && ( temp -> link -> exp < e || temp -> link == NULL ) ) { r = malloc ( sizeof ( struct polynode ) ) ; r -> coeff = c; r -> exp = e ; r -> link = temp -> link ; temp -> link = r ; return ; } temp = temp -> link ; /* go to next node */ } r -> link = NULL ; temp -> link = r ; } } /* CH5PR1.C: Program to create a 3-tuple from a given matrix */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define MAX1 3 #define MAX2 3 struct sparse { int *sp ; int row ; }; void initsparse ( struct sparse * ) ; void create_array ( struct sparse * ) ; void display ( struct sparse ) ; int count ( struct sparse ) ; void create_tuple ( struct sparse *, struct sparse ) ; void display_tuple ( struct sparse ) ; void delsparse ( struct sparse * ) ;

void main( ) { struct sparse s1, s2 ; int c ; clrscr( ); initsparse ( &s1 ) ; initsparse ( &s2 ) ; create_array ( &s1 ) ; printf ( "\nElements in Sparse Matrix: " ) ; display ( s1 ) ; c = count ( s1 ) ; printf ( "\n\nNumber of non-zero elements: %d", c ) ; create_tuple ( &s2, s1 ) ; printf ( "\n\nArray of non-zero elements: " ) ; display_tuple ( s2 ) ; delsparse ( &s1 ) ; delsparse ( &s2 ) ; getch( ) ; } /* initialises element of structure */ void initsparse ( struct sparse *p ) { p -> sp = NULL ; } /* dynamically creates the matrix of size MAX1 x MAX2 */ void create_array ( struct sparse *p ) { int n, i ; p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { printf ( "Enter element no. %d: ", i ) ; scanf ( "%d", &n ) ; * ( p -> sp + i ) = n ; }

} /* displays the contents of the matrix */ void display ( struct sparse p ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % MAX2 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( p.sp + i ) ) ; } } /* counts the number of non-zero elements */ int count ( struct sparse p ) { int cnt = 0, i ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { if ( * ( p.sp + i ) != 0 ) cnt++ ; } return cnt ; } /* creates an array that stores information about non-zero elements */ void create_tuple ( struct sparse *p, struct sparse s ) { int r = 0 , c = -1, l = -1, i ; p -> row = count ( s ) + 1 ; p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ; * ( p -> sp + 0 ) = MAX1 ; * ( p -> sp + 1 ) = MAX2 ; * ( p -> sp + 2 ) = p -> row - 1 ; l=2; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) {

c++ ; /* sets the row and column values */ if ( ( ( i % MAX2 ) == 0 ) && ( i != 0 ) ) { r++ ; c=0; } /* checks for non-zero element row, column and non-zero element value is assigned to the matrix */ if ( * ( s.sp + i ) != 0 ) { l++ ; * ( p -> sp + l ) = r ; l++ ; * ( p -> sp + l ) = c ; l++ ; * ( p -> sp + l ) = * ( s.sp + i ) ; } } } /* displays the contents of 3-tuple */ void display_tuple ( struct sparse p ) { int i ; for ( i = 0 ; i < p.row * 3 ; i++ ) { if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( p.sp + i ) ) ; } } /* deallocates memory */ void delsparse ( struct sparse *p ) { free ( p -> sp ) ; }

/* CH5PR2.C: Program to transpose a sparse matrix */

#include <stdio.h> #include <conio.h> #include <alloc.h> #define MAX1 3 #define MAX2 3 struct sparse { int *sp ; int row ; }; void initsparse ( struct sparse * ) ; void create_array ( struct sparse * ) ; void display ( struct sparse ) ; int count ( struct sparse ) ; void create_tuple ( struct sparse *, struct sparse ) ; void display_tuple ( struct sparse ) ; void transpose ( struct sparse *, struct sparse ) ; void display_transpose ( struct sparse ) ; void delsparse ( struct sparse * ) ; void main( ) { struct sparse s[3] ; int c, i ; for ( i = 0 ; i <= 2 ; i++ ) initsparse ( &s[i] ) ; clrscr( ) ; create_array ( &s[0] ) ; printf ( "\nElements in Sparse Matrix: " ) ; display ( s[0] ) ; c = count ( s[0] ) ; printf ( "\n\nNumber of non-zero elements: %d", c ) ; create_tuple ( &s[1], s[0] ) ; printf ( "\n\nArray of non-zero elements: " ) ; display_tuple ( s[1] ) ; transpose ( &s[2], s[1] ) ;

printf ( "\n\nTranspose of array: " ) ; display_transpose ( s[2] ) ; for ( i = 0 ; i <= 2 ; i++ ) delsparse ( &s[i] ) ; getch( ) ; } /* initialises data members */ void initsparse ( struct sparse *p ) { p -> sp = NULL ; } /* dynamically creates the matrix of size MAX1 x MAX2 */ void create_array ( struct sparse *p ) { int n, i ; p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { printf ( "Enter element no. %d:", i ) ; scanf ( "%d", &n ) ; * ( p -> sp + i ) = n ; } } /* displays the contents of the matrix */ void display ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % MAX2 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ; } }

/* counts the number of non-zero elements */ int count ( struct sparse s ) { int cnt = 0, i ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { if ( * ( s.sp + i ) != 0 ) cnt++ ; } return cnt ; } /* creates an array that stores information about non-zero elements */ void create_tuple ( struct sparse *p, struct sparse s ) { int r = 0 , c = -1, l = -1, i ; p -> row = count ( s ) + 1 ; p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ; * ( p -> sp + 0 ) = MAX1 ; * ( p -> sp + 1 ) = MAX2 ; * ( p -> sp + 2 ) = p -> row - 1 ; l=2; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { c++ ; /* sets the row and column values */ if ( ( ( i % MAX2 ) == 0 ) && ( i != 0 ) ) { r++ ; c=0; } /* checks for non-zero element row, column and non-zero element value is assigned to the matrix */ if ( * ( s.sp + i ) != 0 ) { l++ ; * ( p -> sp + l ) = r ; l++ ;

* ( p -> sp + l ) = c ; l++ ; * ( p -> sp + l ) = * ( s.sp + i ) ; } } } /* displays the contents of 3-tuple */ void display_tuple ( struct sparse p ) { int i ; for ( i = 0 ; i < p.row * 3 ; i++ ) { if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( p.sp + i ) ) ; } } /* obtains transpose of an array */ void transpose ( struct sparse *p, struct sparse s ) { int x, q, pos_1, pos_2, col, elem, c, y ; /* allocate memory */ p -> sp = ( int * ) malloc ( s.row * 3 * sizeof ( int ) ) ; p -> row = s.row ; /* store total number of rows, cols and non-zero elements */ * ( p -> sp + 0 ) = * ( s.sp + 1 ) ; * ( p -> sp + 1 ) = * ( s.sp + 0 ) ; * ( p -> sp + 2 ) = * ( s.sp + 2 ) ; col = * ( p -> sp + 1 ) ; elem = * ( p -> sp + 2 ) ; if ( elem <= 0 ) return ; x=1; for ( c = 0 ; c < col ; c++ ) { for ( y = 1 ; y <= elem ; y++ )

{ q=y*3+1; if ( * ( s.sp + q ) == c ) { pos_2 = x * 3 + 0 ; pos_1 = y * 3 + 1 ; * ( p -> sp + pos_2 ) = * ( s.sp + pos_1 ) ; pos_2 = x * 3 + 1 ; pos_1 = y * 3 + 0 ; * ( p -> sp + pos_2 ) = * ( s.sp + pos_1 ) ; pos_2 = x * 3 + 2 ; pos_1 = y * 3 + 2 ; * ( p -> sp + pos_2 ) = * ( s.sp + pos_1 ) ; x++ ; } } } } /* displays 3-tuple after transpose operation */ void display_transpose ( struct sparse p ) { int i ; for ( i = 0 ; i < p.row * 3 ; i++ ) { if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( p.sp + i ) ) ; } } /* deallocates memory */ void delsparse ( struct sparse *p ) { free ( p -> sp ) ; }

/* CH5PR3.C: Program to add two sparse matrices */ #include <stdio.h> #include <conio.h>

#include <alloc.h> #define MAX1 3 #define MAX2 3 #define MAXSIZE 9 #define BIGNUM 100 struct sparse { int *sp ; int row ; int *result ; }; void initsparse ( struct sparse * ) ; void create_array ( struct sparse * ) ; int count ( struct sparse ) ; void display ( struct sparse ) ; void create_tuple ( struct sparse *, struct sparse ) ; void display_tuple ( struct sparse ) ; void addmat ( struct sparse *, struct sparse, struct sparse ) ; void display_result ( struct sparse ) ; void delsparse ( struct sparse * ) ; void main( ) { struct sparse s[5] ; int i ; clrscr( ) ; for ( i = 0 ; i <= 4 ; i++ ) initsparse ( &s[i] ) ; create_array ( &s[0] ) ; create_tuple ( &s[1], s[0] ) ; display_tuple ( s[1] ) ; create_array ( &s[2] ) ; create_tuple ( &s[3], s[2] ) ; display_tuple ( s[3] ) ; addmat ( &s[4], s[1], s[3] ) ;

printf ( "\nResult of addition of two matrices: " ) ; display_result ( s[4] ) ; for ( i = 0 ; i <= 4 ; i++ ) delsparse ( &s[i] ) ; getch( ) ; } /* initialises structure elements */ void initsparse ( struct sparse *p ) { p -> sp = NULL ; p -> result = NULL ; } /* dynamically creates the matrix */ void create_array ( struct sparse *p ) { int n, i ; /* allocate memory */ p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ; /* add elements to the array */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { printf ( "Enter element no. %d:", i ) ; scanf ( "%d", &n ) ; * ( p -> sp + i ) = n ; } } /* displays the contents of the matrix */ void display ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % MAX2 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ; }

} /* counts the number of non-zero elements */ int count ( struct sparse s ) { int cnt = 0, i ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { if ( * ( s.sp + i ) != 0 ) cnt++ ; } return cnt ; } /* creates an array that stores information about non-zero elements */ void create_tuple ( struct sparse *p, struct sparse s ) { int r = 0 , c = -1, l = -1, i ; /* get the total number of non-zero elements and add 1 to store total no. of rows, cols, and non-zero values */ p -> row = count ( s ) + 1 ; /* allocate memory */ p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ; /* store information about total no. of rows, cols, and non-zero values */ * ( p -> sp + 0 ) = MAX1 ; * ( p -> sp + 1 ) = MAX2 ; * ( p -> sp + 2 ) = p -> row - 1 ; l=2; /* scan the array and store info. about non-zero values in the 3-tuple */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { c++ ; /* sets the row and column values */ if ( ( ( i % MAX2 ) == 0 ) && ( i != 0 ) ) { r++ ; c=0;

} /* checks for non-zero element row, column and non-zero element value is assigned to the matrix */ if ( * ( s.sp + i ) != 0 ) { l++ ; * ( p -> sp + l ) = r ; l++ ; * ( p -> sp + l ) = c ; l++ ; * ( p -> sp + l ) = * ( s.sp + i ) ; } } } /* displays the contents of the matrix */ void display_tuple ( struct sparse s ) { int i, j ; /* traverses the entire matrix */ printf ( "\nElements in a 3-tuple: \n" ) ; j = ( * ( s.sp + 2 ) * 3 ) + 3 ; for ( i = 0 ; i < j ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ; } printf ( "\n" ) ; } /* carries out addition of two matrices */ void addmat ( struct sparse *p, struct sparse s1, struct sparse s2 ) { int i = 1, j = 1, k = 1 ; int elem = 1 ; int max, amax, bmax ; int rowa, rowb, cola, colb, vala, valb ; /* get the total number of non-zero values

from both the matrices */ amax = * ( s1.sp + 2 ) ; bmax = * ( s2.sp + 2 ) ; max = amax + bmax ; /* allocate memory for result */ p -> result = ( int * ) malloc ( MAXSIZE * 3 * sizeof ( int ) ) ; while ( elem <= max ) { /* check if i < max. non-zero values in first 3-tuple and get the values */ if ( i <= amax ) { rowa = * ( s1.sp + i * 3 + 0 ) ; cola = * ( s1.sp + i * 3 + 1 ) ; vala = * ( s1.sp + i * 3 + 2 ) ; } else rowa = cola = BIGNUM ; /* check if j < max. non-zero values in secon 3-tuple and get the values */ if ( j <= bmax ) { rowb = * ( s2.sp + j * 3 + 0 ) ; colb = * ( s2.sp + j * 3 + 1 ) ; valb = * ( s2.sp + j * 3 + 2 ) ; } else rowb = colb = BIGNUM ; /* if row no. of both 3-tuple are same */ if ( rowa == rowb ) { /* if col no. of both 3-tuple are same */ if ( cola == colb ) { /* add tow non-zero values store in result */ * ( p -> result + k * 3 + 0 ) = rowa ; * ( p -> result + k * 3 + 1 ) = cola ; * ( p -> result + k * 3 + 2 ) = vala + valb ; i++ ; j++ ; max-- ;

} /* if col no. of first 3-tuple is < col no. of second 3-tuple, then add info. as it is to result */ if ( cola < colb ) { * ( p -> result + k * 3 + 0 ) = rowa ; * ( p -> result + k * 3 + 1 ) = cola ; * ( p -> result + k * 3 + 2 ) = vala ; i++ ; } /* if col no. of first 3-tuple is > col no. of second 3-tuple, then add info. as it is to result */ if ( cola > colb ) { * ( p -> result + k * 3 + 0 ) = rowb ; * ( p -> result + k * 3 + 1 ) = colb ; * ( p -> result + k * 3 + 2 ) = valb ; j++ ; } k++ ; } /* if row no. of first 3-tuple is < row no. of second 3-tuple, then add info. as it is to result */ if ( rowa < rowb ) { * ( p -> result + k * 3 + 0 ) = rowa ; * ( p -> result + k * 3 + 1 ) = cola ; * ( p -> result + k * 3 + 2 ) = vala ; i++ ; k++ ; } /* if row no. of first 3-tuple is > row no. of second 3-tuple, then add info. as it is to result */ if ( rowa > rowb ) { * ( p -> result + k * 3 + 0 ) = rowb ; * ( p -> result + k * 3 + 1 ) = colb ; * ( p -> result + k * 3 + 2 ) = valb ;

j++ ; k++ ; } elem++ ; } /* add info about the total no. of rows, cols, and non-zero values that the resultant array contains to the result */ * ( p -> result + 0 ) = MAX1 ; * ( p -> result + 1 ) = MAX2 ; * ( p -> result + 2 ) = max ; } /* displays the contents of the matrix */ void display_result ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < ( * ( s.result + 0 + 2 ) + 1 ) * 3 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.result + i ) ) ; } } /* deallocates memory */ void delsparse ( struct sparse *p ) { if ( p -> sp != NULL ) free ( p -> sp ) ; if ( p -> result != NULL ) free ( p -> result ) ; }

/* CH5PR4.C: Program to multiply two sparse matrices */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define MAX1 3

#define MAX2 3 #define MAXSIZE 20 #define TRUE 1 #define FALSE 2 struct sparse { int *sp ; int row ; int *result ; }; void initsparse ( struct sparse * ) ; void create_array ( struct sparse * ) ; int count ( struct sparse ) ; void display ( struct sparse ) ; void create_tuple ( struct sparse*, struct sparse ) ; void display_tuple ( struct sparse ) ; void prodmat ( struct sparse *, struct sparse, struct sparse ) ; void searchina ( int *sp, int ii, int*p, int*flag ) ; void searchinb ( int *sp, int jj, int colofa, int*p, int*flag ) ; void display_result ( struct sparse ) ; void delsparse ( struct sparse * ) ; void main( ) { struct sparse s[5] ; int i ; clrscr( ) ; for ( i = 0 ; i <= 3 ; i++ ) initsparse ( &s[i] ) ; create_array ( &s[0] ) ; create_tuple ( &s[1], s[0] ) ; display_tuple ( s[1] ) ; create_array ( &s[2] ) ; create_tuple ( &s[3], s[2] ) ; display_tuple ( s[3] ) ; prodmat ( &s[4], s[1], s[3] ) ;

printf ( "\nResult of multiplication of two matrices: " ) ; display_result ( s[4] ) ; for ( i = 0 ; i <= 3 ; i++ ) delsparse ( &s[i] ) ; getch( ) ; } /* initialises elements of structure */ void initsparse ( struct sparse *p ) { p -> sp = NULL ; p -> result = NULL ; } /* dynamically creates the matrix */ void create_array ( struct sparse *p ) { int n, i ; /* allocate memory */ p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ; /* add elements to the array */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { printf ( "Enter element no. %d: ", i ) ; scanf ( "%d", &n ) ; * ( p -> sp + i ) = n ; } } /* displays the contents of the matrix */ void display ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ;

} } /* counts the number of non-zero elements */ int count ( struct sparse s ) { int cnt = 0, i ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { if ( * ( s.sp + i ) != 0 ) cnt++ ; } return cnt ; } /* creates an array that stores information about non-zero elements */ void create_tuple ( struct sparse *p, struct sparse s ) { int r = 0 , c = -1, l = -1, i ; /* get the total number of non-zero elements */ p -> row = count ( s ) + 1 ; /* allocate memory */ p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ; /* store information about total no. of rows, cols, and non-zero values */ * ( p -> sp + 0 ) = MAX1 ; * ( p -> sp + 1 ) = MAX2 ; * ( p -> sp + 2 ) = p -> row - 1 ; l=2; /* scan the array and store info. about non-zero values in the 3-tuple */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { c++ ; /* sets the row and column values */ if ( ( ( i % 3 ) == 0 ) && ( i != 0 ) ) { r++ ; c=0;

} /* checks for non-zero element, row, column and non-zero value is assigned to the matrix */ if ( * ( s.sp + i ) != 0 ) { l++ ; * ( p -> sp + l ) = r ; l++ ; * ( p -> sp + l ) = c ; l++ ; * ( p -> sp + l ) = * ( s.sp + i ) ; } } } /* displays the contents of the matrix */ void display_tuple ( struct sparse s ) { int i, j ; /* traverses the entire matrix */ printf ( "\nElements in a 3-tuple: " ) ; j = ( * ( s.sp + 2 ) * 3 ) + 3 ; for ( i = 0 ; i < j ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ; } printf ( "\n" ) ; } /* performs multiplication of sparse matrices */ void prodmat ( struct sparse *p, struct sparse a, struct sparse b ) { int sum, k, position, posi, flaga, flagb, i , j ; k=1; p -> result = ( int * ) malloc ( MAXSIZE * 3 * sizeof ( int ) ) ; for ( i = 0 ; i < * ( a.sp + 0 * 3 + 0 ) ; i++ )

{ for ( j = 0 ; j < * ( b.sp + 0 * 3 + 1 ) ; j++ ) { /* search if an element present at ith row */ searchina ( a.sp, i, &position, &flaga ) ; if ( flaga == TRUE ) { sum = 0 ; /* run loop till there are element at ith row in first 3-tuple */ while ( * ( a.sp + position * 3 + 0 ) == i ) { /* search if an element present at ith col. in second 3-tuple */ searchinb ( b.sp, j, * ( a.sp + position * 3 + 1 ), &posi, &flagb ) ; /* if found then multiply */ if ( flagb == TRUE ) sum = sum + * ( a.sp + position * 3 + 2 ) * * ( b.sp + posi * 3 + 2 ) ; position = position + 1 ; } /* add result */ if ( sum != 0 ) { * ( p -> result + k * 3 + 0 ) = i ; * ( p -> result + k * 3 + 1 ) = j ; * ( p -> result + k * 3 + 2 ) = sum ; k=k+1; } } } } /* add total no. of rows, cols and non-zero values */ * ( p -> result + 0 * 3 + 0 ) = * ( a.sp + 0 * 3 + 0 ) ; * ( p -> result + 0 * 3 + 1 ) = * ( b.sp + 0 * 3 + 1 ) ; * ( p -> result + 0 * 3 + 2 ) = k - 1 ; } /* searches if an element present at iith row */ void searchina ( int *sp, int ii, int *p, int *flag ) {

int j ; *flag = FALSE ; for ( j = 1 ; j <= * ( sp + 0 * 3 + 2 ) ; j++ ) { if ( * ( sp + j * 3 + 0 ) == ii ) { *p = j ; *flag = TRUE ; return ; } } } /* searches if an element where col. of first 3-tuple is equal to row of second 3-tuple */ void searchinb ( int *sp, int jj, int colofa, int *p, int *flag ) { int j ; *flag = FALSE ; for ( j = 1 ; j <= * ( sp + 0 * 3 + 2 ) ; j++ ) { if ( * ( sp + j * 3 + 1 ) == jj && * ( sp + j * 3 + 0 ) == colofa ) { *p = j ; *flag = TRUE ; return ; } } } /* displays the contents of the matrix */ void display_result ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < ( * ( s.result + 0 + 2 ) + 1 ) * 3 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.result + i ) ) ; } } /* deallocates memory */

void delsparse ( struct sparse *s ) { if ( s -> sp != NULL ) free ( s -> sp ) ; if ( s -> result != NULL ) free ( s -> result ) ; } /* CH5PR4.C: Program to multiply two sparse matrices */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define MAX1 3 #define MAX2 3 #define MAXSIZE 20 #define TRUE 1 #define FALSE 2 struct sparse { int *sp ; int row ; int *result ; }; void initsparse ( struct sparse * ) ; void create_array ( struct sparse * ) ; int count ( struct sparse ) ; void display ( struct sparse ) ; void create_tuple ( struct sparse*, struct sparse ) ; void display_tuple ( struct sparse ) ; void prodmat ( struct sparse *, struct sparse, struct sparse ) ; void searchina ( int *sp, int ii, int*p, int*flag ) ; void searchinb ( int *sp, int jj, int colofa, int*p, int*flag ) ; void display_result ( struct sparse ) ; void delsparse ( struct sparse * ) ; void main( ) { struct sparse s[5] ; int i ; clrscr( ) ;

for ( i = 0 ; i <= 3 ; i++ ) initsparse ( &s[i] ) ; create_array ( &s[0] ) ; create_tuple ( &s[1], s[0] ) ; display_tuple ( s[1] ) ; create_array ( &s[2] ) ; create_tuple ( &s[3], s[2] ) ; display_tuple ( s[3] ) ; prodmat ( &s[4], s[1], s[3] ) ; printf ( "\nResult of multiplication of two matrices: " ) ; display_result ( s[4] ) ; for ( i = 0 ; i <= 3 ; i++ ) delsparse ( &s[i] ) ; getch( ) ; } /* initialises elements of structure */ void initsparse ( struct sparse *p ) { p -> sp = NULL ; p -> result = NULL ; } /* dynamically creates the matrix */ void create_array ( struct sparse *p ) { int n, i ; /* allocate memory */ p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ; /* add elements to the array */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { printf ( "Enter element no. %d: ", i ) ; scanf ( "%d", &n ) ; * ( p -> sp + i ) = n ;

} } /* displays the contents of the matrix */ void display ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ; } } /* counts the number of non-zero elements */ int count ( struct sparse s ) { int cnt = 0, i ; for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { if ( * ( s.sp + i ) != 0 ) cnt++ ; } return cnt ; } /* creates an array that stores information about non-zero elements */ void create_tuple ( struct sparse *p, struct sparse s ) { int r = 0 , c = -1, l = -1, i ; /* get the total number of non-zero elements */ p -> row = count ( s ) + 1 ; /* allocate memory */ p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ; /* store information about total no. of rows, cols, and non-zero values */ * ( p -> sp + 0 ) = MAX1 ; * ( p -> sp + 1 ) = MAX2 ;

* ( p -> sp + 2 ) = p -> row - 1 ; l=2; /* scan the array and store info. about non-zero values in the 3-tuple */ for ( i = 0 ; i < MAX1 * MAX2 ; i++ ) { c++ ; /* sets the row and column values */ if ( ( ( i % 3 ) == 0 ) && ( i != 0 ) ) { r++ ; c=0; } /* checks for non-zero element, row, column and non-zero value is assigned to the matrix */ if ( * ( s.sp + i ) != 0 ) { l++ ; * ( p -> sp + l ) = r ; l++ ; * ( p -> sp + l ) = c ; l++ ; * ( p -> sp + l ) = * ( s.sp + i ) ; } } } /* displays the contents of the matrix */ void display_tuple ( struct sparse s ) { int i, j ; /* traverses the entire matrix */ printf ( "\nElements in a 3-tuple: " ) ; j = ( * ( s.sp + 2 ) * 3 ) + 3 ; for ( i = 0 ; i < j ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 )

printf ( "\n" ) ; printf ( "%d\t", * ( s.sp + i ) ) ; } printf ( "\n" ) ; } /* performs multiplication of sparse matrices */ void prodmat ( struct sparse *p, struct sparse a, struct sparse b ) { int sum, k, position, posi, flaga, flagb, i , j ; k=1; p -> result = ( int * ) malloc ( MAXSIZE * 3 * sizeof ( int ) ) ; for ( i = 0 ; i < * ( a.sp + 0 * 3 + 0 ) ; i++ ) { for ( j = 0 ; j < * ( b.sp + 0 * 3 + 1 ) ; j++ ) { /* search if an element present at ith row */ searchina ( a.sp, i, &position, &flaga ) ; if ( flaga == TRUE ) { sum = 0 ; /* run loop till there are element at ith row in first 3-tuple */ while ( * ( a.sp + position * 3 + 0 ) == i ) { /* search if an element present at ith col. in second 3-tuple */ searchinb ( b.sp, j, * ( a.sp + position * 3 + 1 ), &posi, &flagb ) ; /* if found then multiply */ if ( flagb == TRUE ) sum = sum + * ( a.sp + position * 3 + 2 ) * * ( b.sp + posi * 3 + 2 ) ; position = position + 1 ; } /* add result */ if ( sum != 0 ) { * ( p -> result + k * 3 + 0 ) = i ; * ( p -> result + k * 3 + 1 ) = j ; * ( p -> result + k * 3 + 2 ) = sum ;

k=k+1; } } } } /* add total no. of rows, cols and non-zero values */ * ( p -> result + 0 * 3 + 0 ) = * ( a.sp + 0 * 3 + 0 ) ; * ( p -> result + 0 * 3 + 1 ) = * ( b.sp + 0 * 3 + 1 ) ; * ( p -> result + 0 * 3 + 2 ) = k - 1 ; } /* searches if an element present at iith row */ void searchina ( int *sp, int ii, int *p, int *flag ) { int j ; *flag = FALSE ; for ( j = 1 ; j <= * ( sp + 0 * 3 + 2 ) ; j++ ) { if ( * ( sp + j * 3 + 0 ) == ii ) { *p = j ; *flag = TRUE ; return ; } } } /* searches if an element where col. of first 3-tuple is equal to row of second 3-tuple */ void searchinb ( int *sp, int jj, int colofa, int *p, int *flag ) { int j ; *flag = FALSE ; for ( j = 1 ; j <= * ( sp + 0 * 3 + 2 ) ; j++ ) { if ( * ( sp + j * 3 + 1 ) == jj && * ( sp + j * 3 + 0 ) == colofa ) { *p = j ; *flag = TRUE ; return ; } } } /* displays the contents of the matrix */

void display_result ( struct sparse s ) { int i ; /* traverses the entire matrix */ for ( i = 0 ; i < ( * ( s.result + 0 + 2 ) + 1 ) * 3 ; i++ ) { /* positions the cursor to the new line for every new row */ if ( i % 3 == 0 ) printf ( "\n" ) ; printf ( "%d\t", * ( s.result + i ) ) ; } } /* deallocates memory */ void delsparse ( struct sparse *s ) { if ( s -> sp != NULL ) free ( s -> sp ) ; if ( s -> result != NULL ) free ( s -> result ) ; }

/* CH6PR1.C: Program implements array as a stack. */ #include <stdio.h> #include <conio.h> #define MAX 10 struct stack { int arr[MAX] ; int top ; }; void initstack ( struct stack * ) ; void push ( struct stack *, int item ) ; int pop ( struct stack * ) ; void main( ) { struct stack s ; int i ;

clrscr( ) ; initstack ( &s ) ; push ( &s, 11 ) ; push ( &s, 23 ) ; push ( &s, -8 ) ; push ( &s, 16 ) ; push ( &s, 27 ) ; push ( &s, 14 ) ; push ( &s, 20 ) ; push ( &s, 39 ) ; push ( &s, 2 ) ; push ( &s, 15 ) ; push ( &s, 7 ) ; i = pop ( &s ) ; printf ( "\n\nItem popped: %d", i ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; getch( ) ; } /* intializes the stack */ void initstack ( struct stack *s ) { s -> top = -1 ; } /* adds an element to the stack */ void push ( struct stack *s, int item ) { if ( s -> top == MAX - 1 ) { printf ( "\nStack is full." ) ;

return ; } s -> top++ ; s -> arr[s ->top] = item ; } /* removes an element from the stack */ int pop ( struct stack *s ) { int data ; if ( s -> top == -1 ) { printf ( "\nStack is empty." ) ; return NULL ; } data = s -> arr[s -> top] ; s -> top-- ; return data ; } /* CH6PR2.C: Program implements linked list as a stack. */ #include <stdio.h> #include <conio.h> #include <alloc.h> /* structure containing data part and linkpart */ struct node { int data ; struct node *link ; }; void push ( struct node **, int ) ; int pop ( struct node ** ) ; void delstack ( struct node ** ) ; void main( ) { struct node *s = NULL ; int i ; clrscr( ) ; push ( &s, 14 ) ; push ( &s, -3 ) ;

push ( &s, 18 ) ; push ( &s, 29 ) ; push ( &s, 31 ) ; push ( &s, 16 ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; i = pop ( &s ) ; printf ( "\nItem popped: %d", i ) ; delstack ( &s ) ; getch( ) ; } /* adds a new node to the stack as linked list */ void push ( struct node **top, int item ) { struct node *temp ; temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; if ( temp == NULL ) printf ( "\nStack is full." ) ; temp -> data = item ; temp -> link = *top ; *top = temp ; } /* pops an element from the stack */ int pop ( struct node **top ) { struct node *temp ; int item ; if ( *top == NULL ) { printf ( "\nStack is empty." ) ; return NULL ; } temp = *top ;

item = temp -> data ; *top = ( *top ) -> link ; free ( temp ) ; return item ; } /* deallocates memory */ void delstack ( struct node **top ) { struct node *temp ; if ( *top == NULL ) return ; while ( *top != NULL ) { temp = *top ; *top = ( *top ) -> link ; free ( temp ) ; } } /* CH6PR3.C: Program to convert an Infix expression to Prefix form. */ #include <stdio.h> #include <conio.h> #include <string.h> #include <ctype.h> #define MAX 50 struct infix { char target[MAX] ; char stack[MAX] ; char *s, *t ; int top, l ; }; void initinfix ( struct infix * ) ; void setexpr ( struct infix *, char * ) ; void push ( struct infix *, char ) ; char pop ( struct infix * ) ; void convert ( struct infix * ) ; int priority ( char c ) ;

void show ( struct infix ) ; void main( ) { struct infix q ; char expr[MAX] ; clrscr( ) ; initinfix ( &q ) ; printf ( "\nEnter an expression in infix form: " ) ; gets ( expr ) ; setexpr ( &q, expr ) ; convert ( &q ) ; printf ( "The Prefix expression is: " ) ; show ( q ) ; getch( ) ; } /* initializes elements of structure variable */ void initinfix ( struct infix *pq ) { pq -> top = -1 ; strcpy ( pq -> target, "" ) ; strcpy ( pq -> stack, "" ) ; pq -> l = 0 ; } /* reverses the given expression */ void setexpr ( struct infix *pq, char *str ) { pq -> s = str ; strrev ( pq -> s ) ; pq -> l = strlen ( pq -> s ) ; *( pq -> target + pq -> l ) = '\0' ; pq -> t = pq -> target + ( pq -> l - 1 ) ; } /* adds operator to the stack */ void push ( struct infix *pq, char c ) { if ( pq -> top == MAX - 1 )

printf ( "\nStack is full.\n" ) ; else { pq -> top++ ; pq -> stack[pq -> top] = c ; } } /* pops an operator from the stack */ char pop ( struct infix *pq ) { if ( pq -> top == -1 ) { printf ( "Stack is empty\n" ) ; return -1 ; } else { char item = pq -> stack[pq -> top] ; pq -> top-- ; return item ; } } /* converts the infix expr. to prefix form */ void convert ( struct infix *pq ) { char opr ; while ( *( pq -> s ) ) { if ( *( pq -> s ) == ' ' || *( pq -> s ) == '\t' ) { pq -> s++ ; continue ; } if ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) ) { while ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) ) { *( pq -> t ) = *( pq -> s ) ; pq -> s++ ; pq -> t-- ; } }

if ( *( pq -> s ) == ')' ) { push ( pq, *( pq -> s ) ) ; pq -> s++ ; } if ( *( pq -> s ) == '*' || *( pq -> s ) == '+' || *( pq -> s ) == '/' || *( pq -> s ) == '%' || *( pq -> s ) == '-' || *( pq -> s ) == '$' ) { if ( pq -> top != -1 ) { opr = pop ( pq ) ; while ( priority ( opr ) > priority ( *( pq -> s ) ) ) { *( pq -> t ) = opr ; pq -> t-- ; opr = pop ( pq ) ; } push ( pq, opr ) ; push ( pq, *( pq -> s ) ) ; } else push ( pq, *( pq -> s ) ) ; pq -> s++ ; } if ( *( pq -> s ) == '(' ) { opr = pop ( pq ) ; while ( opr != ')' ) { *( pq -> t ) = opr ; pq -> t-- ; opr = pop ( pq ) ; } pq -> s++ ; } } while ( pq -> top != -1 ) { opr = pop ( pq ) ; *( pq -> t ) = opr ; pq -> t-- ;

} pq -> t++ ; } /* returns the priotity of the operator */ int priority ( char c ) { if ( c == '$' ) return 3 ; if ( c == '*' || c == '/' || c == '%' ) return 2 ; else { if ( c == '+' || c == '-' ) return 1 ; else return 0 ; } } /* displays the prefix form of given expr. */ void show ( struct infix pq ) { while ( *( pq.t ) ) { printf ( " %c", *( pq.t ) ) ; pq.t++ ; } } /* CH6PR4.C: Program to convert an Infix form to Postfix form */ #include <stdio.h> #include <conio.h> #include <string.h> #include <ctype.h> #define MAX 50 struct infix { char target[MAX] ; char stack[MAX] ; char *s, *t ; int top ; };

void initinfix ( struct infix * ) ; void setexpr ( struct infix *, char * ) ; void push ( struct infix *, char ) ; char pop ( struct infix * ) ; void convert ( struct infix * ) ; int priority ( char ) ; void show ( struct infix ) ; void main( ) { struct infix p ; char expr[MAX] ; initinfix ( &p ) ; clrscr( ) ; printf ( "\nEnter an expression in infix form: " ) ; gets ( expr ) ; setexpr ( &p, expr ) ; convert ( &p ) ; printf ( "\nThe postfix expression is: " ) ; show ( p ) ; getch( ) ; } /* initializes structure elements */ void initinfix ( struct infix *p ) { p -> top = -1 ; strcpy ( p -> target, "" ) ; strcpy ( p -> stack, "" ) ; p -> t = p -> target ; p -> s = "" ; } /* sets s to point to given expr. */ void setexpr ( struct infix *p, char *str ) { p -> s = str ; }

/* adds an operator to the stack */ void push ( struct infix *p, char c ) { if ( p -> top == MAX ) printf ( "\nStack is full.\n" ) ; else { p -> top++ ; p -> stack[p -> top] = c ; } } /* pops an operator from the stack */ char pop ( struct infix *p ) { if ( p -> top == -1 ) { printf ( "\nStack is empty.\n" ) ; return -1 ; } else { char item = p -> stack[p -> top] ; p -> top-- ; return item ; } } /* converts the given expr. from infix to postfix form */ void convert ( struct infix *p ) { char opr ; while ( *( p -> s ) ) { if ( *( p -> s ) == ' ' || *( p -> s ) == '\t' ) { p -> s++ ; continue ; } if ( isdigit ( *( p -> s ) ) || isalpha ( *( p -> s ) ) ) { while ( isdigit ( *( p -> s ) ) || isalpha ( *( p -> s ) ) ) { *( p -> t ) = *( p -> s ) ; p -> s++ ;

p -> t++ ; } } if ( *( p -> s ) == '(' ) { push ( p, *( p -> s ) ) ; p -> s++ ; } if ( *( p -> s ) == '*' || *( p -> s ) == '+' || *( p -> s ) == '/' || *( p -> s ) == '%' || *( p -> s ) == '-' || *( p -> s ) == '$' ) { if ( p -> top != -1 ) { opr = pop ( p ) ; while ( priority ( opr ) >= priority ( *( p -> s ) ) ) { *( p -> t ) = opr ; p -> t++ ; opr = pop ( p ) ; } push ( p, opr ) ; push ( p, *( p -> s ) ) ; } else push ( p, *( p -> s ) ) ; p -> s++ ; } if ( *( p -> s ) == ')' ) { opr = pop ( p ) ; while ( ( opr ) != '(' ) { *( p -> t ) = opr ; p -> t++ ; opr = pop ( p ) ; } p -> s++ ; } } while ( p -> top != -1 ) { char opr = pop ( p ) ; *( p -> t ) = opr ;

p -> t++ ; } *( p -> t ) = '\0' ; } /* returns the priority of an operator */ int priority ( char c ) { if ( c == '$' ) return 3 ; if ( c == '*' || c == '/' || c == '%' ) return 2 ; else { if ( c == '+' || c == '-' ) return 1 ; else return 0 ; } } /* displays the postfix form of given expr. */ void show ( struct infix p ) { printf ( " %s", p.target ) ; } /* CH6PR5.C: Program to convert expression in postfix form to prefix form */ #include <stdio.h> #include <conio.h> #include <string.h> #define MAX 50 struct postfix { char stack[MAX][MAX], target[MAX] ; char temp1[2], temp2[2] ; char str1[MAX], str2[MAX], str3[MAX] ; int i, top ; }; void initpostfix ( struct postfix * ) ; void setexpr ( struct postfix *, char * ) ;

void push ( struct postfix *, char * ) ; void pop ( struct postfix *, char * ) ; void convert ( struct postfix * ) ; void show ( struct postfix ) ; void main( ) { struct postfix q ; char expr[MAX] ; clrscr( ) ; initpostfix ( &q ) ; printf ( "\nEnter an expression in postfix form: " ) ; gets ( expr ) ; setexpr ( &q, expr ) ; convert ( &q ) ; printf ( "\nThe Prefix expression is: " ) ; show ( q ) ; getch( ) ; } /* initializes the elements of the structure */ void initpostfix ( struct postfix *p ) { p -> i = 0 ; p -> top = -1 ; strcpy ( p -> target, "" ) ; } /* copies given expr. to target string */ void setexpr ( struct postfix *p, char *c ) { strcpy ( p -> target, c ) ; } /* adds an operator to the stack */ void push ( struct postfix *p, char *str ) { if ( p -> top == MAX - 1 ) printf ( "\nStack is full." ) ; else

{ p -> top++ ; strcpy ( p -> stack[p -> top], str ) ; } } /* pops an element from the stack */ void pop ( struct postfix *p, char *a ) { if ( p -> top == -1 ) printf ( "\nStack is empty." ) ; else { strcpy ( a, p -> stack[p -> top] ) ; p -> top-- ; } } /* converts given expr. to prefix form */ void convert ( struct postfix *p ) { while ( p -> target[p -> i] != '\0' ) { /* skip whitespace, if any */ if ( p -> target[p -> i] == ' ') p -> i++ ; if( p -> target[p -> i] == '%' || p -> target[p -> i] == '*' || p -> target[p -> i] == '-' || p -> target[p -> i] == '+' || p -> target[p -> i] == '/' || p -> target[p -> i] == '$' ) { pop ( p, p -> str2 ) ; pop ( p, p -> str3 ) ; p -> temp1[0] = p -> target[ p -> i] ; p -> temp1[1] = '\0' ; strcpy ( p -> str1, p -> temp1 ) ; strcat ( p -> str1, p -> str3 ) ; strcat ( p -> str1, p -> str2 ) ; push ( p, p -> str1 ) ; } else { p -> temp1[0] = p -> target[p -> i] ; p -> temp1[1] = '\0' ; strcpy ( p -> temp2, p -> temp1 ) ; push ( p, p -> temp2 ) ; }

p -> i++ ; } } /* displays the prefix form of expr. */ void show ( struct postfix p ) { char *temp = p.stack[0] ; while ( *temp ) { printf ( "%c ", *temp ) ; temp++ ; } } /* CH6PR6.C: Program to convert an expression in postfix form to an infix form */ #include <stdio.h> #include <conio.h> #include <string.h> #define MAX 50 struct postfix { char stack[MAX][MAX], target[MAX] ; char temp1[2], temp2[2] ; char str1[MAX], str2[MAX], str3[MAX] ; int i, top ; }; void initpostfix ( struct postfix * ) ; void setexpr ( struct postfix *, char * ) ; void push ( struct postfix *, char * ) ; void pop ( struct postfix *, char * ) ; void convert ( struct postfix * ) ; void show ( struct postfix ) ; void main( ) { struct postfix q ; char expr[MAX] ; clrscr( ) ;

initpostfix ( &q ) ; printf ( "\nEnter an expression in postfix form: " ) ; gets ( expr ) ; setexpr ( &q, expr ) ; convert ( &q ) ; printf ( "\nThe infix expression is: " ) ; show ( q ) ; getch( ) ; } /* initializes data member */ void initpostfix ( struct postfix *p ) { p -> i = 0 ; p -> top = -1 ; strcpy ( p -> target, "" ) ; } /* copies given expression to target string */ void setexpr ( struct postfix *p, char *c ) { strcpy ( p -> target, c ) ; } /* adds an expr. to the stack */ void push ( struct postfix *p, char *str ) { if ( p -> top == MAX - 1 ) printf ( "\nStack is full." ) ; else { p -> top++ ; strcpy ( p -> stack[p -> top], str ) ; } } /* pops an expr. from the stack */ void pop ( struct postfix *p, char *a ) { if ( p -> top == -1 ) printf ( "\nStack is empty." ) ;

else { strcpy ( a, p -> stack[p -> top] ) ; p -> top-- ; } } /* converts given expr. to infix form */ void convert ( struct postfix *p ) { while ( p -> target[p -> i] ) { /* skip whitespace, if any */ if( p -> target[p -> i] == ' ' ) p -> i++ ; if ( p -> target[p -> i] == '%' || p -> target[p -> i] == '*' || p -> target[p -> i] == '-' || p -> target[p -> i] == '+' || p -> target[p -> i] == '/' || p -> target[p -> i] == '$' ) { pop ( p, p -> str2 ) ; pop ( p, p -> str3 ) ; p -> temp1[0] = p -> target[p -> i] ; p -> temp1[1] = '\0' ; strcpy ( p -> str1, p -> str3 ) ; strcat ( p -> str1, p -> temp1 ) ; strcat ( p -> str1, p -> str2 ) ; push ( p, p -> str1 ) ; } else { p -> temp1[0] = p -> target[p -> i] ; p -> temp1[1] = '\0' ; strcpy ( p -> temp2, p -> temp1 ) ; push ( p, p -> temp2 ) ; } p -> i++ ; } } /* displays the expression */ void show ( struct postfix p ) { char *t ; t = p.stack[0] ; while ( *t ) {

printf ( "%c ", *t ) ; t++ ; } } /* CH6PR7.C: Program to evaluate an epression entered in postfix form */ #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #define MAX 50 struct postfix { int stack[MAX] ; int top, nn ; char *s ; }; void initpostfix ( struct postfix * ) ; void setexpr ( struct postfix *, char * ) ; void push ( struct postfix *, int ) ; int pop ( struct postfix * ) ; void calculate ( struct postfix * ) ; void show ( struct postfix ) ; void main( ) { struct postfix q ; char expr[MAX] ; clrscr( ) ; initpostfix ( &q ) ;

printf ( "\nEnter postfix expression to be evaluated: " ) ; gets ( expr ) ; setexpr ( &q, expr ) ; calculate ( &q ) ; show ( q ) ;

getch( ) ; } /* initializes data members */ void initpostfix ( struct postfix *p ) { p -> top = -1 ; } /* sets s to point to the given expr. */ void setexpr ( struct postfix *p, char *str ) { p -> s = str ; } /* adds digit to the stack */ void push ( struct postfix *p, int item ) { if ( p -> top == MAX - 1 ) printf ( "\nStack is full." ) ; else { p -> top++ ; p -> stack[p -> top] = item ; } } /* pops digit from the stack */ int pop ( struct postfix *p ) { int data ; if ( p -> top == -1 ) { printf ( "\nStack is empty." ) ; return NULL ; } data = p -> stack[p -> top] ; p -> top-- ; return data ; } /* evaluates the postfix expression */ void calculate( struct postfix *p )

{ int n1, n2, n3 ; while ( *( p -> s ) ) { /* skip whitespace, if any */ if ( *( p -> s ) == ' ' || *( p -> s ) == '\t' ) { p -> s++ ; continue ; } /* if digit is encountered */ if ( isdigit ( *( p -> s ) ) ) { p -> nn = *( p -> s ) - '0' ; push ( p, p -> nn ) ; } else { /* if operator is encountered */ n1 = pop ( p ) ; n2 = pop ( p ) ; switch ( *( p -> s ) ) { case '+' : n3 = n2 + n1 ; break ; case '-' : n3 = n2 - n1 ; break ; case '/' : n3 = n2 / n1 ; break ; case '*' : n3 = n2 * n1 ; break ; case '%' : n3 = n2 % n1 ; break ; case '$' : n3 = pow ( n2 , n1 ) ;

break ; default : printf ( "Unknown operator" ) ; exit ( 1 ) ; } push ( p, n3 ) ; } p -> s++ ; } } /* displays the result */ void show ( struct postfix p ) { p.nn = pop ( &p ) ; printf ( "Result is: %d", p.nn ) ; } /* CH7PR1.C: Program that implements queue as an array. */ #include <stdio.h> #include <conio.h> #define MAX 10 void addq ( int *, int, int *, int * ) ; int delq ( int *, int *, int * ) ; void main( ) { int arr[MAX] ; int front = -1, rear = -1, i ; clrscr( ) ; addq ( arr, 23, &front, &rear ) ; addq ( arr, 9, &front, &rear ) ; addq ( arr, 11, &front, &rear ) ; addq ( arr, -10, &front, &rear ) ; addq ( arr, 25, &front, &rear ) ; addq ( arr, 16, &front, &rear ) ; addq ( arr, 17, &front, &rear ) ; addq ( arr, 22, &front, &rear ) ; addq ( arr, 19, &front, &rear ) ;

addq ( arr, 30, &front, &rear ) ; addq ( arr, 32, &front, &rear ) ; i = delq ( arr, &front, &rear ) ; printf ( "\nItem deleted: %d", i ) ; i = delq ( arr, &front, &rear ) ; printf ( "\nItem deleted: %d", i ) ; i = delq ( arr, &front, &rear ) ; printf ( "\nItem deleted: %d", i ) ; getch( ) ; } /* adds an element to the queue */ void addq ( int *arr, int item, int *pfront, int *prear ) { if ( *prear == MAX - 1 ) { printf ( "\nQueue is full." ) ; return ; } ( *prear )++ ; arr[*prear] = item ; if ( *pfront == -1 ) *pfront = 0 ; } /* removes an element from the queue */ int delq ( int *arr, int *pfront, int *prear ) { int data ; if ( *pfront == -1 ) { printf ( "\nQueue is Empty." ) ; return NULL ; } data = arr[*pfront] ; arr[*pfront] = 0 ; if ( *pfront == *prear ) *pfront = *prear = -1 ;

else ( *pfront )++ ; return data ; } /* CH7PR2.C: Program that implements queue as a linked list. */ #include <stdio.h> #include <conio.h> struct node { int data ; struct node *link ; }; struct queue { struct node *front ; struct node *rear ; }; void initqueue ( struct queue * ) ; void addq ( struct queue *, int ) ; int delq ( struct queue * ) ; void delqueue ( struct queue * ) ; void main( ) { struct queue a ; int i ; clrscr( ) ; initqueue ( &a ) ; addq ( &a, 11 ) ; addq ( &a, -8 ) ; addq ( &a, 23 ) ; addq ( &a, 19 ) ; addq ( &a, 15 ) ; addq ( &a, 16 ) ; addq ( &a, 28 ) ; i = delq ( &a ) ;

printf ( "\nItem extracted: %d", i ) ; i = delq ( &a ) ; printf ( "\nItem extracted: %d", i ) ; i = delq ( &a ) ; printf ( "\nItem extracted: %d", i ) ; delqueue ( &a ) ; getch( ) ; } /* initialises data member */ void initqueue ( struct queue *q ) { q -> front = q -> rear = NULL ; } /* adds an element to the queue */ void addq ( struct queue *q, int item ) { struct node *temp ; temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; if ( temp == NULL ) printf ( "\nQueue is full." ) ; temp -> data = item ; temp -> link = NULL ; if ( q -> front == NULL ) { q -> rear = q -> front = temp ; return ; } q -> rear -> link = temp ; q -> rear = q -> rear -> link ; } /* removes an element from the queue */ int delq ( struct queue * q ) { struct node *temp ; int item ;

if ( q -> front == NULL ) { printf ( "\nQueue is empty." ) ; return NULL ; } item = q -> front -> data ; temp = q -> front ; q -> front = q -> front -> link ; free ( temp ) ; return item ; } /* deallocates memory */ void delqueue ( struct queue *q ) { struct node *temp ; if ( q -> front == NULL ) return ; while ( q -> front != NULL ) { temp = q -> front ; q -> front = q -> front -> link ; free ( temp ) ; } } /* CH7PR5.C: Program that implements circular queue as an array. */ #include <stdio.h> #include <conio.h> #define MAX 10 void addq ( int *, int, int *, int * ) ; int delq ( int *, int *, int * ) ; void display ( int * ) ; void main( ) { int arr[MAX] ; int i, front, rear ;

clrscr( ) ; /* initialise data member */ front = rear = -1 ; for ( i = 0 ; i < MAX ; i++ ) arr[i] = 0 ; addq ( arr, 14, &front, &rear ) ; addq ( arr, 22, &front, &rear ) ; addq ( arr, 13, &front, &rear ) ; addq ( arr, -6, &front, &rear ) ; addq ( arr, 25, &front, &rear ) ; printf ( "\nElements in the circular queue: " ) ; display ( arr ) ; i = delq ( arr, &front, &rear ) ; printf ( "Item deleted: %d", i ) ; i = delq ( arr, &front, &rear ) ; printf ( "\nItem deleted: %d", i ) ; printf ( "\nElements in the circular queue after deletion: " ) ; display ( arr ) ; addq ( arr, 21, &front, &rear ) ; addq ( arr, 17, &front, &rear ) ; addq ( arr, 18, &front, &rear ) ; addq ( arr, 9, &front, &rear ) ; addq ( arr, 20, &front, &rear ) ; printf ( "Elements in the circular queue after addition: " ) ; display ( arr ) ; addq ( arr, 32, &front, &rear ) ; printf ( "Elements in the circular queue after addition: " ) ; display ( arr ) ; getch( ) ; } /* adds an element to the queue */ void addq ( int *arr, int item, int *pfront, int *prear ) { if ( ( *prear == MAX - 1 && *pfront == 0 ) || ( *prear + 1 == *pfront ) )

{ printf ( "\nQueue is full." ) ; return ; } if ( *prear == MAX - 1 ) *prear = 0 ; else ( *prear )++ ; arr[*prear] = item ; if ( *pfront == -1 ) *pfront = 0 ; } /* removes an element from the queue */ int delq ( int *arr, int *pfront, int *prear ) { int data ; if ( *pfront == -1 ) { printf ( "\nQueue is empty." ) ; return NULL ; } data = arr[*pfront] ; arr[*pfront] = 0 ; if ( *pfront == *prear ) { *pfront = -1 ; *prear = -1 ; } else { if ( *pfront == MAX - 1 ) *pfront = 0 ; else ( *pfront )++ ; } return data ; } /* displays element in a queue */

void display ( int * arr ) { int i ; printf ( "\n" ) ; for ( i = 0 ; i < MAX ; i++ ) printf ( "%d\t", arr[i] ) ; printf ( "\n" ) ; } /* CH7PR4.C: Program that implements deque using an array. */ #include <stdio.h> #include <conio.h> #define MAX 10 void addqatbeg ( int *, int, int *, int * ) ; void addqatend ( int *, int, int *, int * ) ; int delqatbeg ( int *, int *, int * ) ; int delqatend ( int *, int *, int * ) ; void display ( int * ) ; int count ( int * ) ; void main( ) { int arr[MAX] ; int front, rear, i, n ; clrscr( ) ; /* initialises data members */ front = rear = -1 ; for ( i = 0 ; i < MAX ; i++ ) arr[i] = 0 ; addqatend ( arr, 17, &front, &rear ) ; addqatbeg ( arr, 10, &front, &rear ) ; addqatend ( arr, 8, &front, &rear ) ; addqatbeg ( arr, -9, &front, &rear ) ; addqatend ( arr, 13, &front, &rear ) ; addqatbeg ( arr, 28, &front, &rear ) ; addqatend ( arr, 14, &front, &rear ) ; addqatbeg ( arr, 5, &front, &rear ) ; addqatend ( arr, 25, &front, &rear ) ; addqatbeg ( arr, 6, &front, &rear ) ; addqatend ( arr, 21, &front, &rear ) ;

addqatbeg ( arr, 11, &front, &rear ) ; printf ( "\nElements in a deque: " ) ; display ( arr ) ; n = count ( arr ) ; printf ( "\nTotal number of elements in deque: %d", n ) ; i = delqatbeg ( arr, &front, &rear ) ; printf ( "\nItem extracted: %d", i ) ; i = delqatbeg ( arr, &front, &rear ) ; printf ( "\nItem extracted:%d", i ) ; i = delqatbeg ( arr, &front, &rear ) ; printf ( "\nItem extracted:%d", i ) ; i = delqatbeg ( arr, &front, &rear ) ; printf ( "\nItem extracted: %d", i ) ; printf ( "\nElements in a deque after deletion: " ) ; display ( arr ) ; addqatend ( arr, 16, &front, &rear ) ; addqatend ( arr, 7, &front, &rear ) ; printf ( "\nElements in a deque after addition: " ) ; display ( arr ) ; i = delqatend ( arr, &front, &rear ) ; printf ( "\nItem extracted: %d", i ) ; i = delqatend ( arr, &front, &rear ) ; printf ( "\nItem extracted: %d", i ) ; printf ( "\nElements in a deque after deletion: " ) ; display ( arr ) ; n = count ( arr ) ; printf ( "\nTotal number of elements in deque: %d", n ) ; getch( ) ; } /* adds an element at the beginning of a deque */ void addqatbeg ( int *arr, int item, int *pfront, int *prear )

{ int i, k, c ; if ( *pfront == 0 && *prear == MAX - 1 ) { printf ( "\nDeque is full.\n" ) ; return ; } if ( *pfront == -1 ) { *pfront = *prear = 0 ; arr[*pfront] = item ; return ; } if ( *prear != MAX - 1 ) { c = count ( arr ) ; k = *prear + 1 ; for ( i = 1 ; i <= c ; i++ ) { arr[k] = arr[k - 1] ; k-- ; } arr[k] = item ; *pfront = k ; ( *prear )++ ; } else { ( *pfront )-- ; arr[*pfront] = item ; } } /* adds an element at the end of a deque */ void addqatend ( int *arr, int item, int *pfront, int *prear ) { int i, k ; if ( *pfront == 0 && *prear == MAX - 1 ) { printf ( "\nDeque is full.\n" ) ; return ; }

if ( *pfront == -1 ) { *prear = *pfront = 0 ; arr[*prear] = item ; return ; } if ( *prear == MAX - 1 ) { k = *pfront - 1 ; for ( i = *pfront - 1 ; i < *prear ; i++ ) { k=i; if ( k == MAX - 1 ) arr[k] = 0 ; else arr[k] = arr[i + 1] ; } ( *prear )-- ; ( *pfront )-- ; } ( *prear )++ ; arr[*prear] = item ; } /* removes an element from the *pfront end of deque */ int delqatbeg ( int *arr, int *pfront, int *prear ) { int item ; if ( *pfront == -1 ) { printf ( "\nDeque is empty.\n" ) ; return 0 ; } item = arr[*pfront] ; arr[*pfront] = 0 ; if ( *pfront == *prear ) *pfront = *prear = -1 ; else ( *pfront )++ ; return item ;

} /* removes an element from the *prear end of the deque */ int delqatend ( int *arr, int *pfront, int *prear ) { int item ; if ( *pfront == -1 ) { printf ( "\nDeque is empty.\n" ) ; return 0 ; } item = arr[*prear] ; arr[*prear] = 0 ; ( *prear )-- ; if ( *prear == -1 ) *pfront = -1 ; return item ; } /* displays elements of a deque */ void display ( int *arr ) { int i ; printf ( "\n front->" ) ; for ( i = 0 ; i < MAX ; i++ ) printf ( "\t%d", arr[i] ) ; printf ( " <-rear" ) ; } /* counts the total number of elements in deque */ int count ( int *arr ) { int c = 0, i ; for ( i = 0 ; i < MAX ; i++ ) { if ( arr[i] != 0 ) c++ ; } return c ; } /* CH7PR5.C: Program that implements a priority queue using an array. */

#include <stdio.h> #include <conio.h> #define MAX 5 struct data { char job[MAX] ; int prno ; int ord ; }; struct pque { struct data d[MAX] ; int front ; int rear ; }; void initpque ( struct pque * ) ; void add ( struct pque *, struct data ) ; struct data delete ( struct pque * ) ; void main( ) { struct pque q ; struct data dt, temp ; int i, j = 0 ; clrscr( ) ; initpque ( &q ) ; printf ( "Enter Job description (max 4 chars) and its priority\n" ) ; printf ( "Lower the priority number, higher the priority\n" ) ; printf ( "Job Priority\n" ) ; for ( i = 0 ; i < MAX ; i++ ) { scanf ( "%s %d", &dt.job, &dt.prno ) ; dt.ord = j++ ; add ( &q, dt ) ; } printf ( "\n" ) ;

printf ( "Process jobs prioritywise\n" ) ; printf ( "Job\tPriority\n" ) ; for ( i = 0 ; i < MAX ; i++ ) { temp = delete ( &q ) ; printf ( "%s\t%d\n", temp.job, temp.prno ) ; } printf ( "\n" ) ; getch( ) ; } /* initialises data members */ void initpque ( struct pque *pq ) { int i ; pq -> front = pq -> rear = -1 ; for ( i = 0 ; i < MAX ; i++ ) { strcpy ( pq -> d[i].job, '\0' ) ; pq -> d[i].prno = pq -> d[i].ord = 0 ; } } /* adds item to the priority queue */ void add ( struct pque *pq, struct data dt ) { struct data temp ; int i, j ; if ( pq -> rear == MAX - 1 ) { printf ( "\nQueue is full." ) ; return ; } pq -> rear++ ; pq -> d[pq -> rear] = dt ; if ( pq -> front == -1 ) pq -> front = 0 ; for ( i = pq -> front ; i <= pq -> rear ; i++ ) {

for ( j = i + 1 ; j <= pq -> rear ; j++ ) { if ( pq -> d[i].prno > pq -> d[j].prno ) { temp = pq -> d[i] ; pq -> d[i] = pq -> d[j] ; pq -> d[j] = temp ; } else { if ( pq -> d[i].prno == pq -> d[j].prno ) { if ( pq -> d[i].ord > pq -> d[j].ord ) { temp = pq -> d[i] ; pq -> d[i] = pq -> d[j] ; pq -> d[j] = temp ; } } } } } } /* removes item from priority queue */ struct data delete ( struct pque *pq ) { struct data t ; strcpy ( t.job, "" ) ; t.prno = 0 ; t.ord = 0 ; if ( pq -> front == -1 ) { printf ( "\nQueue is Empty.\n" ) ; return t ; } t = pq -> d[pq -> front] ; pq -> d[pq -> front] = t ; if ( pq -> front == pq -> rear ) pq -> front = pq -> rear = -1 ; else pq -> front++ ; return t ;

} /* CH8PR1.C: Program to build a binary search tree from arrays. */ #include <stdio.h> #include <conio.h> #include <alloc.h> struct node { struct node *left ; char data ; struct node *right ; }; struct node * buildtree ( int ) ; void inorder ( struct node * ) ; char arr[ ] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', '\0', '\0', 'H' } ; int lc[ ] = { 1, 3, 5, -1, 9, -1, -1, -1, -1, -1 } ; int rc[ ] = { 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 } ; void main( ) { struct node *root ; clrscr( ) ; root = buildtree ( 0 ) ; printf ( In-order Traversal:\n ) ; inorder ( root ) ; getch( ) ; } struct node * buildtree ( int index ) { struct node *temp = NULL ; if ( index != -1 ) { temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> left = buildtree ( lc[index] ) ; temp -> data = arr[index] ; temp -> right = buildtree ( rc[index] ) ; } return temp ;

} void inorder ( struct node *root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( "%c\t", root -> data ) ; inorder ( root -> right ) ; } } /* CH8PR2.C: Program to build a binary search tree from an array. */ #include <stdio.h> #include <conio.h> #include <alloc.h> struct node { struct node *left ; char data ; struct node *right ; }; struct node * buildtree ( int ) ; void inorder ( struct node * ) ; char a[ ] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', '\0', '\0', 'H', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' }; void main( ) { struct node *root ; clrscr( ) ; root = buildtree ( 0 ) ; printf ( "In-order Traversal:\n" ) ; inorder ( root ) ; getch( ) ; } struct node * buildtree ( int n )

{ struct node *temp = NULL ; if ( a[n] != '\0' ) { temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> left = buildtree ( 2 * n + 1 ) ; temp -> data = a[n] ; temp -> right = buildtree ( 2 * n + 2 ) ; } return temp ; } void inorder ( struct node *root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( "%c\t", root -> data ) ; inorder ( root -> right ) ; } } /* CH8PR3.C: Program to implement a binary search tree. */ #include <stdio.h> #include <conio.h> #include <alloc.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; }; void insert ( struct btreenode **, int ) ; void inorder ( struct btreenode * ) ; void preorder ( struct btreenode * ) ; void postorder ( struct btreenode * ) ; void main( ) { struct btreenode *bt ; int req, i = 1, num ; bt = NULL ; /* empty tree */

clrscr( ) ; printf ( "Specify the number of items to be inserted: " ) ; scanf ( "%d", &req ) ; while ( i++ <= req ) { printf ( "Enter the data: " ) ; scanf ( "%d", &num ) ; insert ( &bt, num ) ; } printf ( "\nIn-order Traversal: " ) ; inorder ( bt ) ; printf ( "\nPre-order Traversal: " ) ; preorder ( bt ) ; printf ( "\nPost-order Traversal: " ) ; postorder ( bt ) ; } /* inserts a new node in a binary search tree */ void insert ( struct btreenode **sr, int num ) { if ( *sr == NULL ) { *sr = malloc ( sizeof ( struct btreenode ) ) ; ( *sr ) -> leftchild = NULL ; ( *sr ) -> data = num ; ( *sr ) -> rightchild = NULL ; return ; } else /* search the node to which new node will be attached */ { /* if new data is less, traverse to left */ if ( num < ( *sr ) -> data ) insert ( &( ( *sr ) -> leftchild ), num ) ; else /* else traverse to right */ insert ( &( ( *sr ) -> rightchild ), num ) ; } return ; } /* traverse a binary search tree in a LDR (Left-Data-Right) fashion */

void inorder ( struct btreenode *sr ) { if ( sr != NULL ) { inorder ( sr -> leftchild ) ; /* print the data of the node whose leftchild is NULL or the path has already been traversed */ printf ( "\t%d", sr -> data ) ; inorder ( sr -> rightchild ) ; } else return ; } /* traverse a binary search tree in a DLR (Data-Left-right) fashion */ void preorder ( struct btreenode *sr ) { if ( sr != NULL ) { /* print the data of a node */ printf ( "\t%d", sr -> data ) ; /* traverse till leftchild is not NULL */ preorder ( sr -> leftchild ) ; /* traverse till rightchild is not NULL */ preorder ( sr -> rightchild ) ; } else return ; }

/* traverse a binary search tree in LRD (Left-Right-Data) fashion */ void postorder ( struct btreenode *sr ) { if ( sr != NULL ) { postorder ( sr -> leftchild ) ; postorder ( sr -> rightchild ) ; printf ( "\t%d", sr -> data ) ; } else return ; }

/* CH8PR4.C: Program to insert and delete a node from the binary search tree. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define TRUE 1 #define FALSE 0 struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; }; void insert ( struct btreenode **, int ) ; void delete ( struct btreenode **, int ) ; void search ( struct btreenode **, int, struct btreenode **, struct btreenode **, int * ) ; void inorder ( struct btreenode * ) ; void main( ) { struct btreenode *bt ; int req, i = 0, num, a[ ] = { 11, 9, 13, 8, 10, 12, 14, 15, 7 } ; bt = NULL ; /* empty tree */ clrscr( ) ; while ( i <= 8 ) { insert ( &bt, a[i] ) ; i++ ; } clrscr( ) ; printf ( "Binary tree before deletion:\n" ) ; inorder ( bt ) ; delete ( &bt, 10 ) ; printf ( "\nBinary tree after deletion:\n" ) ; inorder ( bt ) ; delete ( &bt, 14 ) ;

printf ( "\nBinary tree after deletion:\n" ) ; inorder ( bt ) ; delete ( &bt, 8 ) ; printf ( "\nBinary tree after deletion:\n" ) ; inorder ( bt ) ; delete ( &bt, 13 ) ; printf ( "\nBinary tree after deletion:\n" ) ; inorder ( bt ) ; } /* inserts a new node in a binary search tree */ void insert ( struct btreenode **sr, int num ) { if ( *sr == NULL ) { *sr = malloc ( sizeof ( struct btreenode ) ) ; ( *sr ) -> leftchild = NULL ; ( *sr ) -> data = num ; ( *sr ) -> rightchild = NULL ; } else /* search the node to which new node will be attached */ { /* if new data is less, traverse to left */ if ( num < ( *sr ) -> data ) insert ( &( ( *sr ) -> leftchild ), num ) ; else /* else traverse to right */ insert ( &( ( *sr ) -> rightchild ), num ) ; } } /* deletes a node from the binary search tree */ void delete ( struct btreenode **root, int num ) { int found ; struct btreenode *parent, *x, *xsucc ; /* if tree is empty */ if ( *root == NULL ) { printf ( "\nTree is empty" ) ; return ; }

parent = x = NULL ; /* call to search function to find the node to be deleted */ search ( root, num, &parent, &x, &found ) ; /* if the node to deleted is not found */ if ( found == FALSE ) { printf ( "\nData to be deleted, not found" ) ; return ; } /* if the node to be deleted has two children */ if ( x -> leftchild != NULL && x -> rightchild != NULL ) { parent = x ; xsucc = x -> rightchild ; while ( xsucc -> leftchild != NULL ) { parent = xsucc ; xsucc = xsucc -> leftchild ; } x -> data = xsucc -> data ; x = xsucc ; } /* if the node to be deleted has no child */ if ( x -> leftchild == NULL && x -> rightchild == NULL ) { if ( parent -> rightchild == x ) parent -> rightchild = NULL ; else parent -> leftchild = NULL ; free ( x ) ; return ; } /* if the node to be deleted has only rightchild */ if ( x -> leftchild == NULL && x -> rightchild != NULL ) { if ( parent -> leftchild == x ) parent -> leftchild = x -> rightchild ;

else parent -> rightchild = x -> rightchild ; free ( x ) ; return ; } /* if the node to be deleted has only left child */ if ( x -> leftchild != NULL && x -> rightchild == NULL ) { if ( parent -> leftchild == x ) parent -> leftchild = x -> leftchild ; else parent -> rightchild = x -> leftchild ; free ( x ) ; return ; } } /*returns the address of the node to be deleted, address of its parent and whether the node is found or not */ void search ( struct btreenode **root, int num, struct btreenode **par, struct btreenode **x, int *found ) { struct btreenode *q ; q = *root ; *found = FALSE ; *par = NULL ; while ( q != NULL ) { /* if the node to be deleted is found */ if ( q -> data == num ) { *found = TRUE ; *x = q ; return ; } *par = q ; if ( q -> data > num ) q = q -> leftchild ; else

q = q -> rightchild ; } } /* traverse a binary search tree in a LDR (Left-Data-Right) fashion */ void inorder ( struct btreenode *sr ) { if ( sr != NULL ) { inorder ( sr -> leftchild ) ; /* print the data of the node whose leftchild is NULL or the path has already been traversed */ printf ( "%d\t", sr -> data ) ; inorder ( sr -> rightchild ) ; } } /* CH8PR5.C: Program to maintain a threaded binary tree. */ #include <stdio.h> #include <conio.h> #include <alloc.h> enum boolean { false = 0, true = 1 }; struct thtree { enum boolean isleft ; struct thtree *left ; int data ; struct thtree *right ; enum boolen isright ; }; void insert ( struct thtree **, int ) ; void delete ( struct thtree **, int ) ; void search ( struct thtree **, int, struct thtree **, struct thtree **, int * ) ; void inorder ( struct thtree * ) ; void deltree ( struct thtree ** ) ;

void main( ) { struct thtree *th_head ; th_head = NULL ; /* empty tree */ insert ( &th_head, 11 ) ; insert ( &th_head, 9 ) ; insert ( &th_head, 13 ) ; insert ( &th_head, 8 ) ; insert ( &th_head, 10 ) ; insert ( &th_head, 12 ) ; insert ( &th_head, 14 ) ; insert ( &th_head, 15 ) ; insert ( &th_head, 7 ) ; clrscr( ) ; printf ( "Threaded binary tree before deletion:\n" ) ; inorder ( th_head ) ; delete ( &th_head, 10 ) ; printf ( "\nThreaded binary tree after deletion:\n" ) ; inorder ( th_head ) ; delete ( &th_head, 14 ) ; printf ( "\nThreaded binary tree after deletion:\n" ) ; inorder ( th_head ) ; delete ( &th_head, 8 ) ; printf ( "\nThreaded binary tree after deletion:\n" ) ; inorder ( th_head ) ; delete ( &th_head, 13 ) ; printf ( "\nThreaded binary tree after deletion:\n" ) ; inorder ( th_head ) ; deltree ( &th_head ) ; getch( ) ; } /* inserts a node in a threaded binary tree */ void insert ( struct thtree **s, int num ) { struct thtree *p, *z, *head = *s ;

/* allocating a new node */ z = malloc ( sizeof ( struct thtree ) ) ; z -> isleft = true ; /* indicates a thread */ z -> data = num ; /* assign new data */ z -> isright = true ; /* indicates a thread */ /* if tree is empty */ if ( *s == NULL ) { head = malloc ( sizeof ( struct thtree ) ) ; /* the entire tree is treated as a left sub-tree of the head node */ head -> isleft = false ; head -> left = z ; /* z becomes leftchild of the head node */ head -> data = -9999 ; /* no data */ head -> right = head ; /* right link will always be pointing to itself */ head -> isright = false ; *s = head ; z -> left = head ; /* left thread to head */ z -> right = head ; /* right thread to head */ } else /* if tree is non-empty */ { p = head -> left ; /* traverse till the thread is found attached to the head */ while ( p != head ) { if ( p -> data > num ) { if ( p -> isleft != true ) /* checking for a thread */ p = p -> left ; else { z -> left = p -> left ; p -> left = z ; p -> isleft = false ; /* indicates a link */ z -> isright = true ; z -> right = p ; return ; }

} else { if ( p -> data < num ) { if ( p -> isright != true ) p = p -> right ; else { z -> right = p -> right ; p -> right = z ; p -> isright = false ; /* indicates a link */ z -> isleft = true ; z -> left = p ; return ; } } } } } } /* deletes a node from the binary search tree */ void delete ( struct thtree **root, int num ) { int found ; struct thtree *parent, *x, *xsucc ; /* if tree is empty */ if ( *root == NULL ) { printf ( "\nTree is empty" ) ; return ; } parent = x = NULL ; /* call to search function to find the node to be deleted */ search ( root, num, &parent, &x, &found ) ; /* if the node to deleted is not found */ if ( found == false ) { printf ( "\nData to be deleted, not found" ) ; return ; }

/* if the node to be deleted has two children */ if ( x -> isleft == false && x -> isright == false ) { parent = x ; xsucc = x -> right ; while ( xsucc -> isleft == false ) { parent = xsucc ; xsucc = xsucc -> left ; } x -> data = xsucc -> data ; x = xsucc ; } /* if the node to be deleted has no child */ if ( x -> isleft == true && x -> isright == true ) { /* if node to be deleted is a root node */ if ( parent == NULL ) { ( *root ) -> left = *root ; ( *root ) -> isleft = true ; free ( x ) ; return ; } if ( parent -> right == x ) { parent -> isright = true ; parent -> right = x -> right ; } else { parent -> isleft = true ; parent -> left = x -> left ; } free ( x ) ; return ; } /* if the node to be deleted has only rightchild */

if ( x -> isleft == true && x -> isright == false ) { /* node to be deleted is a root node */ if ( parent == NULL ) { ( *root ) -> left = x -> right ; free ( x ) ; return ; } if ( parent -> left == x ) { parent -> left = x -> right ; x -> right -> left = x -> left ; } else { parent -> right = x -> right ; x -> right -> left = parent ; } free ( x ) ; return ; } /* if the node to be deleted has only left child */ if ( x -> isleft == false && x -> isright == true ) { /* the node to be deleted is a root node */ if ( parent == NULL ) { parent = x ; xsucc = x -> left ; while ( xsucc -> right == false ) xsucc = xsucc -> right ; xsucc -> right = *root ; ( *root ) -> left = x -> left ; free ( x ) ; return ; } if ( parent -> left == x )

{ parent -> left = x -> left ; x -> left -> right = parent ; } else { parent -> right = x -> left ; x -> left -> right = x -> right ; } free ( x ) ; return ; } } /* returns the address of the node to be deleted, address of its parent and whether the node is found or not */ void search ( struct thtree **root, int num, struct thtree **par, struct thtree **x, int *found ) { struct thtree *q ; q = ( *root ) -> left ; *found = false ; *par = NULL ; while ( q != *root ) { /* if the node to be deleted is found */ if ( q -> data == num ) { *found = true ; *x = q ; return ; } *par = q ; if ( q -> data > num ) { if ( q -> isleft == true ) { *found = false ; x = NULL ; return ; }

q = q -> left ; } else { if ( q -> isright == true ) { *found = false ; *x = NULL ; return ; } q = q -> right ; } } } /* traverses the threaded binary tree in inorder */ void inorder ( struct thtree *root ) { struct thtree *p ; p = root -> left ; while ( p != root ) { while ( p -> isleft == false ) p = p -> left ; printf ( "%d\t", p -> data ) ; while ( p -> isright == true ) { p = p -> right ; if ( p == root ) break ; printf ( "%d\t", p -> data ) ; } p = p -> right ; } } void deltree ( struct thtree **root ) { while ( ( *root ) -> left != *root )

delete ( root, ( *root ) -> left -> data ) ; } /* CH8PR6.C: Program to reconstruct a binary search tree. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define MAX 101 struct node { struct node *left ; int data ; struct node *right ; }; void insert ( struct node **, int ) ; void preorder ( struct node * ) ; void postorder ( struct node * ) ; void inorder ( struct node * ) ; struct node * recons ( int *, int *, int ) ; void deltree ( struct node * ) ; int in[MAX], pre[MAX], x ; void main( ) { struct node *t, *p, *q ; int req, i, num ; t = NULL ; /* empty tree */ clrscr( ) ; printf ( "Specify the number of items to be inserted: " ) ; while ( 1 ) { scanf ( "%d", &req ) ; if ( req >= MAX || req <= 0 ) printf ( "\nEnter number between 1 to 100.\n" ) ; else break ; } for ( i = 0 ; i < req ; i++ )

{ printf ( "Enter the data: " ) ; scanf ( "%d", &num ) ; insert ( &t, num ) ; } printf ( "\nIn-order Traversal:\n" ) ; x=0; inorder ( t ) ; printf ( "\nPre-order Traversal:\n" ) ; x=0; preorder ( t ) ; printf ( "\nPost-order Traversal:\n" ) ; x=0; postorder ( t ) ; deltree ( t ) ; t = NULL ; t = recons ( in, pre, req ) ; printf ( "\n\nAfter reconstruction of the binary tree.\n" ) ; x=0; printf ( "\nIn-order Traversal:\n" ) ; inorder ( t ) ; x=0; printf ( "\nPre-order Traversal:\n" ) ; preorder ( t ) ; x=0; printf ( "\nPost-order Traversal:\n" ) ; postorder ( t ) ; deltree ( t ) ; getch( ) ; } /* inserts a new node in a binary search tree */ void insert ( struct node **sr, int num ) { if ( *sr == NULL ) { *sr = ( struct node * ) malloc ( sizeof ( struct node ) ) ;

( *sr ) -> left = NULL ; ( *sr ) -> data = num ; ( *sr ) -> right = NULL ; return ; } else /* search the node to which new node will be attached */ { /* if new data is less, traverse to left */ if ( num < ( *sr ) -> data ) insert ( &( ( *sr ) -> left ), num ) ; else /* else traverse to right */ insert ( &( ( *sr ) -> right ), num ) ; } } void preorder ( struct node *t ) { if ( t != NULL ) { printf ( "%d\t", pre[x++]= t -> data ) ; preorder ( t -> left ) ; preorder ( t -> right ) ; } } void postorder ( struct node *t ) { if ( t != NULL ) { postorder ( t -> left ) ; postorder ( t -> right ) ; printf ( "%d\t", t -> data ) ; } } void inorder ( struct node *t ) { if ( t != NULL ) { inorder ( t -> left ) ; printf ( "%d\t", in[x++]= t -> data ) ; inorder ( t -> right ) ; } }

struct node * recons ( int *inorder, int *preorder, int noofnodes ) { struct node *temp, *left, *right ; int tempin[100], temppre[100], i, j ; if ( noofnodes == 0 ) return NULL ; temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = preorder[0] ; temp -> left = NULL ; temp -> right = NULL ; if ( noofnodes == 1 ) return temp ; for ( i = 0 ; inorder[i] != preorder[0] ; ) i++ ; if ( i > 0 ) { for ( j = 0 ; j <= i ; j++ ) tempin[j] = inorder[j] ; for ( j = 0 ; j < i ; j++ ) temppre[j] = preorder[j + 1] ; } left = recons ( tempin, temppre, i ) ; temp -> left = left ; if ( i < noofnodes - 1 ) { for ( j = i ; j < noofnodes - 1 ; j++ ) { tempin[j - i] = inorder[j + 1] ; temppre[j - i] = preorder[j + 1] ; } } right = recons ( tempin, temppre, noofnodes - i - 1 ) ; temp -> right = right ; return temp ; } void deltree ( struct node *t )

{ if ( t != NULL ) { deltree ( t -> left ) ; deltree ( t -> right ) ; } free ( t ) ; } /* CH8PR7.C: Program to maintain an AVL tree. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define FALSE 0 #define TRUE 1 struct AVLNode { int data ; int balfact ; struct AVLNode *left ; struct AVLNode *right ; }; struct AVLNode * buildtree ( struct AVLNode *, int, int * ) ; struct AVLNode * deldata ( struct AVLNode *, int, int * ) ; struct AVLNode * del ( struct AVLNode *, struct AVLNode *, int * ) ; struct AVLNode * balright ( struct AVLNode *, int * ) ; struct AVLNode * balleft ( struct AVLNode *, int * ) ; void display ( struct AVLNode * ) ; void deltree ( struct AVLNode * ) ; void main( ) { struct AVLNode *avl = NULL ; int h ; clrscr( ) ; avl = buildtree ( avl, 20, &h ) ; avl = buildtree ( avl, 6, &h ) ; avl = buildtree ( avl, 29, &h ) ; avl = buildtree ( avl, 5, &h ) ; avl = buildtree ( avl, 12, &h ) ;

avl = buildtree ( avl, 25, &h ) ; avl = buildtree ( avl, 32, &h ) ; avl = buildtree ( avl, 10, &h ) ; avl = buildtree ( avl, 15, &h ) ; avl = buildtree ( avl, 27, &h ) ; avl = buildtree ( avl, 13, &h ) ; printf ( "\nAVL tree:\n" ) ; display ( avl ) ; avl = deldata ( avl, 20, &h ) ; avl = deldata ( avl, 12, &h ) ; printf ( "\nAVL tree after deletion of a node:\n" ) ; display ( avl ) ; deltree ( avl ) ; getch( ) ; } /* inserts an element into tree */ struct AVLNode * buildtree ( struct AVLNode *root, int data, int *h ) { struct AVLNode *node1, *node2 ; if ( !root ) { root = ( struct AVLNode * ) malloc ( sizeof ( struct AVLNode ) ) ; root -> data = data ; root -> left = NULL ; root -> right = NULL ; root -> balfact = 0 ; *h = TRUE ; return ( root ) ; } if ( data < root -> data ) { root -> left = buildtree ( root -> left, data, h ) ; /* If left subtree is higher */ if ( *h ) { switch ( root -> balfact ) { case 1:

node1 = root -> left ; if ( node1 -> balfact == 1 ) { printf ( "\nRight rotation along %d.", root -> data ) ; root -> left = node1 -> right ; node1 -> right = root ; root -> balfact = 0 ; root = node1 ; } else { printf ( "\nDouble rotation, left along %d", node1 -> data ) ; node2 = node1 -> right ; node1 -> right = node2 -> left ; printf ( " then right along %d.\n", root -> data ) ; node2 -> left = node1 ; root -> left = node2 -> right ; node2 -> right = root ; if ( node2 -> balfact == 1 ) root -> balfact = -1 ; else root -> balfact = 0 ; if ( node2 -> balfact == -1 ) node1 -> balfact = 1 ; else node1 -> balfact = 0 ; root = node2 ; } root -> balfact = 0 ; *h = FALSE ; break ; case 0: root -> balfact = 1 ; break ; case -1: root -> balfact = 0 ; *h = FALSE ; } } }

if ( data > root -> data ) { root -> right = buildtree ( root -> right, data, h ) ; /* If the right subtree is higher */ if ( *h ) { switch ( root -> balfact ) { case 1: root -> balfact = 0 ; *h = FALSE ; break ; case 0: root -> balfact = -1 ; break; case -1: node1 = root -> right ; if ( node1 -> balfact == -1 ) { printf ( "\nLeft rotation along %d.", root -> data ) ; root -> right = node1 -> left ; node1 -> left = root ; root -> balfact = 0 ; root = node1 ; } else { printf ( "\nDouble rotation, right along %d", node1 -> data ) ; node2 = node1 -> left ; node1 -> left = node2 -> right ; node2 -> right = node1 ; printf ( " then left along %d.\n", root -> data ); root -> right = node2 -> left ; node2 -> left = root ; if ( node2 -> balfact == -1 ) root -> balfact = 1 ; else root -> balfact = 0 ; if ( node2 -> balfact == 1 ) node1 -> balfact = -1 ;

else node1 -> balfact = 0 ; root = node2 ; } root -> balfact = 0 ; *h = FALSE ; } } } return ( root ) ; } /* deletes an item from the tree */ struct AVLNode * deldata ( struct AVLNode *root, int data, int *h ) { struct AVLNode *node ; if ( !root ) { printf ( "\nNo such data." ) ; return ( root ) ; } else { if ( data < root -> data ) { root -> left = deldata ( root -> left, data, h ) ; if ( *h ) root = balright ( root, h ) ; } else { if ( data > root -> data ) { root -> right = deldata ( root -> right, data, h ) ; if ( *h ) root = balleft ( root, h ) ; } else { node = root ; if ( node -> right == NULL ) { root = node -> left ; *h = TRUE ; free ( node ) ;

} else { if ( node -> left == NULL ) { root = node -> right ; *h = TRUE ; free ( node ) ; } else { node -> right = del ( node -> right, node, h ) ; if ( *h ) root = balleft ( root, h ) ; } } } } } return ( root ) ; } struct AVLNode * del ( struct AVLNode *succ, struct AVLNode *node, int *h ) { struct AVLNode *temp = succ ; if ( succ -> left != NULL ) { succ -> left = del ( succ -> left, node, h ) ; if ( *h ) succ = balright ( succ, h ) ; } else { temp = succ ; node -> data = succ -> data ; succ = succ -> right ; free ( temp ) ; *h = TRUE ; } return ( succ ) ; } /* balances the tree, if right sub-tree is higher */ struct AVLNode * balright ( struct AVLNode *root, int *h ) {

struct AVLNode *node1, *node2 ; switch ( root -> balfact ) { case 1: root -> balfact = 0 ; break; case 0: root -> balfact = -1 ; *h = FALSE ; break; case -1: node1 = root -> right ; if ( node1 -> balfact <= 0 ) { printf ( "\nLeft rotation along %d.", root -> data ) ; root -> right = node1 -> left ; node1 -> left = root ; if ( node1 -> balfact == 0 ) { root -> balfact = -1 ; node1 -> balfact = 1 ; *h = FALSE ; } else { root -> balfact = node1 -> balfact = 0 ; } root = node1 ; } else { printf ( "\nDouble rotation, right along %d", node1 -> data ); node2 = node1 -> left ; node1 -> left = node2 -> right ; node2 -> right = node1 ; printf ( " then left along %d.\n", root -> data ); root -> right = node2 -> left ; node2 -> left = root ; if ( node2 -> balfact == -1 ) root -> balfact = 1 ; else

root -> balfact = 0 ; if ( node2 -> balfact == 1 ) node1 -> balfact = -1 ; else node1 -> balfact = 0 ; root = node2 ; node2 -> balfact = 0 ; } } return ( root ) ; } /* balances the tree, if left sub-tree is higher */ struct AVLNode * balleft ( struct AVLNode *root, int *h ) { struct AVLNode *node1, *node2 ; switch ( root -> balfact ) { case -1: root -> balfact = 0 ; break ; case 0: root -> balfact = 1 ; *h = FALSE ; break ; case 1: node1 = root -> left ; if ( node1 -> balfact >= 0 ) { printf ( "\nRight rotation along %d.", root -> data ) ; root -> left = node1 -> right ; node1 -> right = root ; if ( node1 -> balfact == 0 ) { root -> balfact = 1 ; node1 -> balfact = -1 ; *h = FALSE ; } else { root -> balfact = node1 -> balfact = 0 ; } root = node1 ;

} else { printf ( "\nDouble rotation, left along %d", node1 -> data ) ; node2 = node1 -> right ; node1 -> right = node2 -> left ; node2 -> left = node1 ; printf ( " then right along %d.\n", root -> data ) ; root -> left = node2 -> right ; node2 -> right = root ; if ( node2 -> balfact == 1 ) root -> balfact = -1 ; else root -> balfact = 0 ; if ( node2-> balfact == -1 ) node1 -> balfact = 1 ; else node1 -> balfact = 0 ; root = node2 ; node2 -> balfact = 0 ; } } return ( root ) ; } /* displays the tree in-order */ void display ( struct AVLNode *root ) { if ( root != NULL ) { display ( root -> left ) ; printf ( "%d\t", root -> data ) ; display ( root -> right ) ; } } /* deletes the tree */ void deltree ( struct AVLNode *root ) { if ( root != NULL ) { deltree ( root -> left ) ; deltree ( root -> right ) ; } free ( root ) ;

} /* CH8PR8.C: Program which maintains a B-tree of order 5. */ #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <alloc.h> #define MAX 4 #define MIN 2 struct btnode { int count ; int value[MAX + 1] ; struct btnode *child[MAX + 1] ; }; struct btnode * insert ( int, struct btnode * ) ; int setval ( int, struct btnode *, int *, struct btnode ** ) ; struct btnode * search ( int, struct btnode *, int * ) ; int searchnode ( int, struct btnode *, int * ) ; void fillnode ( int, struct btnode *, struct btnode *, int ) ; void split ( int, struct btnode *, struct btnode *, int, int *, struct btnode ** ) ; struct btnode * delete ( int, struct btnode * ) ; int delhelp ( int, struct btnode * ) ; void clear ( struct btnode *, int ) ; void copysucc ( struct btnode *, int ) ; void restore ( struct btnode *, int ) ; void rightshift ( struct btnode *, int ) ; void leftshift ( struct btnode *, int ) ; void merge ( struct btnode *, int ) ; void display ( struct btnode * ) ; void main( ) { struct node *root ; root = NULL ; clrscr( ) ; root = insert ( 27, root ) ; root = insert ( 42, root ) ; root = insert ( 22, root ) ;

root = insert ( 47, root ) ; root = insert ( 32, root ) ; root = insert ( 2, root ) ; root = insert ( 51, root ) ; root = insert ( 40, root ) ; root = insert ( 13, root ) ; printf ( "B-tree of order 5:\n" ) ; display ( root ) ; root = delete ( 22, root ) ; root = delete ( 11, root ) ; printf ( "\n\nAfter deletion of values:\n" ) ; display ( root ) ; getch( ) ; } /* inserts a value in the B-tree*/ struct btnode * insert ( int val, struct btnode *root ) { int i ; struct btnode *c, *n ; int flag ; flag = setval ( val, root, &i, &c ) ; if ( flag ) { n = ( struct btnode * ) malloc ( sizeof ( struct btnode ) ) ; n -> count = 1 ; n -> value [1] = i ; n -> child [0] = root ; n -> child [1] = c ; return n ; } return root ; } /* sets the value in the node */ int setval ( int val, struct btnode *n, int *p, struct btnode **c ) { int k ; if ( n == NULL ) { *p = val ;

*c = NULL ; return 1 ; } else { if ( searchnode ( val, n, &k ) ) printf ( "\nKey value already exists.\n" ) ; if ( setval ( val, n -> child [k], p, c ) ) { if ( n -> count < MAX ) { fillnode ( *p, *c, n, k ) ; return 0 ; } else { split ( *p, *c, n, k, p, c ) ; return 1 ; } } return 0 ; } } /* searches value in the node */ struct btnode * search ( int val, struct btnode *root, int *pos ) { if ( root == NULL ) return NULL ; else { if ( searchnode ( val, root, pos ) ) return root ; else return search ( val, root -> child [*pos], pos ) ; } } /* searches for the node */ int searchnode ( int val, struct btnode *n, int *pos ) { if ( val < n -> value [1] ) { *pos = 0 ; return 0 ; }

else { *pos = n -> count ; while ( ( val < n -> value [*pos] ) && *pos > 1 ) ( *pos )-- ; if ( val == n -> value [*pos] ) return 1 ; else return 0 ; } }

/* adjusts the value of the node */ void fillnode ( int val, struct btnode *c, struct btnode *n, int k ) { int i ; for ( i = n -> count ; i > k ; i-- ) { n -> value [i + 1] = n -> value [i] ; n -> child [i + 1] = n -> child [i] ; } n -> value [k + 1] = val ; n -> child [k + 1] = c ; n -> count++ ; } /* splits the node */ void split ( int val, struct btnode *c, struct btnode *n, int k, int *y, struct btnode **newnode ) { int i, mid ; if ( k <= MIN ) mid = MIN ; else mid = MIN + 1 ; *newnode = ( struct btnode * ) malloc ( sizeof ( struct btnode ) ) ; for ( i = mid + 1 ; i <= MAX ; i++ ) { ( *newnode ) -> value [i - mid] = n -> value [i] ; ( *newnode ) -> child [i - mid] = n -> child [i] ; }

( *newnode ) -> count = MAX - mid ; n -> count = mid ; if ( k <= MIN ) fillnode ( val, c, n, k ) ; else fillnode ( val, c, *newnode, k - mid ) ; *y = n -> value [n -> count] ; ( *newnode ) -> child [0] = n -> child [n -> count] ; n -> count-- ; } /* deletes value from the node */ struct btnode * delete ( int val, struct btnode *root ) { struct btnode * temp ; if ( ! delhelp ( val, root ) ) printf ( "\nValue %d not found.", val ) ; else { if ( root -> count == 0 ) { temp = root ; root = root -> child [0] ; free ( temp ) ; } } return root ; } /* helper function for delete( ) */ int delhelp ( int val, struct btnode *root ) { int i ; int flag ; if ( root == NULL ) return 0 ; else { flag = searchnode ( val, root, &i ) ; if ( flag ) { if ( root -> child [i - 1] ) { copysucc ( root, i ) ;

flag = delhelp ( root -> value [i], root -> child [i] ) ; if ( !flag ) printf ( "\nValue %d not found.", val ) ; } else clear ( root, i ) ; } else flag = delhelp ( val, root -> child [i] ) ; if ( root -> child [i] != NULL ) { if ( root -> child [i] -> count < MIN ) restore ( root, i ) ; } return flag ; } } /* removes the value from the node and adjusts the values */ void clear ( struct btnode *node, int k ) { int i ; for ( i = k + 1 ; i <= node -> count ; i++ ) { node -> value [i - 1] = node -> value [i] ; node -> child [i - 1] = node -> child [i] ; } node -> count-- ; } /* copies the successor of the value that is to be deleted */ void copysucc ( struct btnode *node, int i ) { struct btnode *temp ; temp = node -> child [i] ; while ( temp -> child[0] ) temp = temp -> child [0] ; node -> value [i] = temp -> value [1] ; } /* adjusts the node */ void restore ( struct btnode *node, int i )

{ if ( i == 0 ) { if ( node -> child [1] -> count > MIN ) leftshift ( node, 1 ) ; else merge ( node, 1 ) ; } else { if ( i == node -> count ) { if ( node -> child [i - 1] -> count > MIN ) rightshift ( node, i ) ; else merge ( node, i ) ; } else { if ( node -> child [i - 1] -> count > MIN ) rightshift ( node, i ) ; else { if ( node -> child [i + 1] -> count > MIN ) leftshift ( node, i + 1 ) ; else merge ( node, i ) ; } } } } /* adjusts the values and children while shifting the value from parent to right child */ void rightshift ( struct btnode *node, int k ) { int i ; struct btnode *temp ; temp = node -> child [k] ; for ( i = temp -> count ; i > 0 ; i-- ) { temp -> value [i + 1] = temp -> value [i] ; temp -> child [i + 1] = temp -> child [i] ; }

temp -> child [1] = temp -> child [0] ; temp -> count++ ; temp -> value [1] = node -> value [k] ; temp = node -> child [k - 1] ; node -> value [k] = temp -> value [temp -> count] ; node -> child [k] -> child [0] = temp -> child [temp -> count] ; temp -> count-- ; } /* adjusts the values and children while shifting the value from parent to left child */ void leftshift ( struct btnode *node, int k ) { int i ; struct btnode *temp ; temp = node -> child [k - 1] ; temp -> count++ ; temp -> value [temp -> count] = node -> value [k] ; temp -> child [temp -> count] = node -> child [k] -> child [0] ; temp = node -> child [k] ; node -> value [k] = temp -> value [1] ; temp -> child [0] = temp -> child [1] ; temp -> count-- ; for ( i = 1 ; i <= temp -> count ; i++ ) { temp -> value [i] = temp -> value [i + 1] ; temp -> child [i] = temp -> child [i + 1] ; } } /* merges two nodes */ void merge ( struct btnode *node, int k ) { int i ; struct btnode *temp1, *temp2 ; temp1 = node -> child [k] ; temp2 = node -> child [k - 1] ; temp2 -> count++ ; temp2 -> value [temp2 -> count] = node -> value [k] ; temp2 -> child [temp2 -> count] = node -> child [0] ;

for ( i = 1 ; i <= temp1 -> count ; i++ ) { temp2 -> count++ ; temp2 -> value [temp2 -> count] = temp1 -> value [i] ; temp2 -> child [temp2 -> count] = temp1 -> child [i] ; } for ( i = k ; i < node -> count ; i++ ) { node -> value [i] = node -> value [i + 1] ; node -> child [i] = node -> child [i + 1] ; } node -> count-- ; free ( temp1 ) ; } /* displays the B-tree */ void display ( struct btnode *root ) { int i ; if ( root != NULL ) { for ( i = 0 ; i < root -> count ; i++ ) { display ( root -> child [i] ) ; printf ( "%d\t", root -> value [i + 1] ) ; } display ( root -> child [i] ) ; } } /* CH8PR9.C: Program to maintain a heap. */ #include <stdio.h> #include <conio.h> void restoreup ( int, int * ) ; void restoredown ( int, int *, int ) ; void makeheap ( int *, int ) ; void add ( int, int *, int * ) ; int replace ( int, int *, int ) ; int del ( int *, int * ) ; void main( ) {

int arr [20] = { 1000, 7, 10, 25, 17, 23, 27, 16, 19, 37, 42, 4, 33, 1, 5, 11 } ; int i, n = 15 ; clrscr( ) ; makeheap ( arr, n ) ; printf ( "Heap:\n" ) ; for ( i = 1 ; i <= n ; i++ ) printf ( "%d\t", arr [i] ) ; i = 24 ; add ( i, arr, &n ) ; printf ( "\n\nElement added %d.\n", i ) ; printf ( "\nHeap after addition of an element:\n" ) ; for ( i = 1 ; i <= n ; i++ ) printf ( "%d\t", arr [i] ) ; i = replace ( 2, arr, n ) ; printf ( "\n\nElement replaced %d.\n", i ) ; printf ( "\nHeap after replacement of an element:\n" ) ; for ( i = 1 ; i <= n ; i++ ) printf ( "%d\t", arr [i] ) ; i = del ( arr, &n ) ; printf ( "\n\nElement deleted %d.\n", i ) ; printf ( "\nHeap after deletion of an element:\n" ) ; for ( i = 1 ; i <= n ; i++ ) printf ( "%d\t", arr [i] ) ; getch( ) ; } void restoreup ( int i, int *arr ) { int val ; val = arr [i] ; while ( arr [i / 2] <= val ) { arr [i] = arr [i / 2] ; i=i/2; } arr [i] = val ; }

void restoredown ( int pos, int *arr, int n ) { int i, val ; val = arr [pos] ; while ( pos <= n / 2 ) { i = 2 * pos ; if ( ( i < n ) && ( arr [i] < arr [i + 1] ) ) i++ ; if ( val >= arr [i] ) break ; arr [pos] = arr [i] ; pos = i ; } arr [pos] = val ; } void makeheap ( int *arr, int n ) { int i ; for ( i = n / 2 ; i >= 1 ; i-- ) restoredown ( i, arr, n ) ; } void add ( int val, int *arr, int *n ) { ( *n ) ++ ; arr [*n] = val ; restoreup ( *n, arr ) ; } int replace ( int i, int *arr, int n ) { int r = arr [1] ; arr [1] = i ; for ( i = n / 2 ; i >= 1 ; i-- ) restoredown ( i, arr, n ) ; return r ; } int del ( int *arr, int *n ) { int val ; val = arr [1] ; arr [1] = arr [*n] ; ( *n ) -- ; restoredown ( 1, arr, *n ) ;

return val ; } /* CH9PR1.C: Linear search in an unsorted array. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ; int i, num ; clrscr( ) ; printf ( "Enter number to search: " ) ; scanf ( "%d", &num ) ; for ( i = 0 ; i <= 9 ; i++ ) { if ( arr[i] == num ) break ; } if ( i == 10 ) printf ( "Number is not present in the array." ) ; else printf ( "The number is at position %d in the array.", i ) ; getch( ) ; } /* CH9PR2.C: Linear search in a sorted array. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[10] = { 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 } ; int i, num ; clrscr( ) ; printf ( "Enter number to search: " ) ; scanf ( "%d", &num ) ;

for ( i = 0 ; i <= 9 ; i++ ) { if ( arr[9] < num || arr[i] >= num ) { if ( arr[i] == num ) printf ( "The number is at position %d in the array.", i ) ; else printf ( "Number is not present in the array." ) ; break ; } } getch( ) ; } /* CH9PR3.C: Binary search in a sorted array. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[10] = { 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 } ; int mid, lower = 0 , upper = 9, num, flag = 1 ; clrscr( ) ; printf ( "Enter number to search: " ) ; scanf ( "%d", &num ) ; for ( mid = ( lower + upper ) / 2 ; lower <= upper ; mid = ( lower + upper ) / 2 ) { if ( arr[mid] == num ) { printf ( "The number is at position %d in the array.", mid ) ; flag = 0 ; break ; } if ( arr[mid] > num ) upper = mid - 1 ; else lower = mid + 1 ; }

if ( flag ) printf ( "Element is not present in the array." ) ; getch( ) ; } /* CH9PR4.C: Bubble sort. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[5] = { 25, 17, 31, 13, 2 } ; int i, j, temp ; clrscr( ) ; printf ( "Bubble sort.\n" ) ; printf ( "\nArray before sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; for ( i = 0 ; i <= 3 ; i++ ) { for ( j = 0 ; j <= 3 - i ; j++ ) { if ( arr[j] > arr[j + 1] ) { temp = arr[j] ; arr[j] = arr[j + 1] ; arr[j + 1] = temp ; } } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; getch( ) ; }

/* CH9PR5.C: Selection sort. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[5] = { 25, 17, 31, 13, 2 } ; int i, j, temp ; clrscr( ) ; printf ( "Selection sort.\n" ) ; printf ( "\nArray before sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; for ( i = 0 ; i <= 3 ; i++ ) { for ( j = i + 1 ; j <= 4 ; j++ ) { if ( arr[i] > arr[j] ) { temp = arr[i] ; arr[i] = arr[j] ; arr[j] = temp ; } } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; getch( ) ; } /* CJ9PR6.C: Quick sort. */ #include <stdio.h> #include <conio.h> int split ( int*, int, int ) ;

void main( ) { int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ; int i ; void quicksort ( int *, int, int ) ; clrscr( ) ; printf ( "Quick sort.\n" ) ; printf ( "\nArray before sorting:\n") ; for ( i = 0 ; i <= 9 ; i++ ) printf ( "%d\t", arr[i] ) ; quicksort ( arr, 0, 9 ) ; printf ( "\nArray after sorting:\n") ; for ( i = 0 ; i <= 9 ; i++ ) printf ( "%d\t", arr[i] ) ; getch( ) ; } 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 ) ; } } int split ( int a[ ], int lower, int upper ) { int i, p, q, t ; p = lower + 1 ; q = upper ; i = a[lower] ; while ( q >= p ) {

while ( a[p] < i ) p++ ; while ( a[q] > i ) q-- ; if ( q > p ) { t = a[p] ; a[p] = a[q] ; a[q] = t ; } } t = a[lower] ; a[lower] = a[q] ; a[q] = t ; return q ; } /* CH9PR7.C: Insertion sort. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[5] = { 25, 17, 31, 13, 2 } ; int i, j, k, temp ; clrscr( ) ; printf ( "Insertion sort.\n" ) ; printf ( "\nArray before sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; for ( i = 1 ; i <= 4 ; i++ ) { for ( j = 0 ; j < i ; j++ ) { if ( arr[j] > arr[i] ) { temp = arr[j] ;

arr[j] = arr[i] ; for ( k = i ; k > j ; k-- ) arr[k] = arr[k - 1] ; arr[k + 1] = temp ; } } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; getch( ) ; } /* CH9PR8.C: Binary Tree Sorting. */ #include <stdio.h> #include <conio.h> #include <alloc.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; }; void insert ( struct btreenode **, int ) ; void inorder ( struct btreenode * ) ; void main( ) { struct btreenode *bt ; int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ; int i ; bt = NULL ; clrscr( ) ; printf ( "Binary tree sort.\n" ) ;

printf ( "\nArray:\n" ) ; for ( i = 0 ; i <= 9 ; i++ ) printf ( "%d\t", arr[i] ) ; for ( i = 0 ; i <= 9 ; i++ ) insert ( &bt, arr[i] ) ; printf ( "\nIn-order traversal of binary tree:\n" ) ; inorder ( bt ) ; getch( ) ; } void insert ( struct btreenode **sr, int num ) { if ( *sr == NULL ) { *sr = malloc ( sizeof ( struct btreenode ) ) ; ( *sr ) -> leftchild = NULL ; ( *sr ) -> data = num ; ( *sr ) -> rightchild = NULL ; } else { if ( num < ( *sr ) -> data ) insert ( &( ( *sr ) -> leftchild ), num ) ; else insert ( &( ( *sr ) -> rightchild ), num ) ; } } void inorder ( struct btreenode *sr ) { if ( sr != NULL ) { inorder ( sr -> leftchild ) ; printf ( "%d\t", sr -> data ) ; inorder ( sr -> rightchild ) ; } } /* CH9PR9.C: Heap Sort. */ #include <stdio.h> #include <conio.h>

void makeheap ( int [ ], int ) ; void heapsort ( int [ ], int ) ; void main( ) { int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ; int i ; clrscr( ) ; printf ( "Heap Sort.\n" ) ; makeheap ( arr, 10 ) ; printf ( "\nBefore Sorting:\n" ) ; for ( i = 0 ; i <= 9 ; i++ ) printf ( "%d\t", arr[i] ) ; heapsort ( arr, 10 ) ; printf ( "\nAfter Sorting:\n" ) ; for ( i = 0 ; i <= 9 ; i++ ) printf ( "%d\t", arr[i] ) ; getch( ); } void makeheap ( int x[ ], int n ) { int i, val, s, f ; for ( i = 1 ; i < n ; i++ ) { val = x[i] ; s=i; f=(s-1)/2; while ( s > 0 && x[f] < val ) { x[s] = x[f] ; s=f; f=(s-1)/2; } x[s] = val ; } } void heapsort ( int x[ ], int n )

{ int i, s, f, ivalue ; for ( i = n - 1 ; i > 0 ; i-- ) { ivalue = x[i] ; x[i] = x[0] ; f=0; if ( i == 1 ) s = -1 ; else s=1; if ( i > 2 && x[2] > x[1] ) s=2; while ( s >= 0 && ivalue < x[s] ) { x[f] = x[s] ; f=s; s=2*f+1; if ( s + 1 <= i - 1 && x[s] < x[s + 1] ) s++ ; if ( s > i - 1 ) s = -1 ; } x[f] = ivalue ; } }

/* CH9PR10.C: Merge Sort. */ #include <stdio.h> #include <conio.h> void main( ) { int a[5] = { 11, 2, 9, 13, 57 } ; int b[5] = { 25, 17, 1, 90, 3 } ; int c[10] ; int i, j, k, temp ; clrscr( ) ; printf ( "Merge sort.\n" ) ; printf ( "\nFirst array:\n" ) ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", a[i] ) ; printf ( "\n\nSecond array:\n" ) ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", b[i] ) ; for ( i = 0 ; i <= 3 ; i++ ) { for ( j = i + 1 ; j <= 4 ; j++ ) { if ( a[i] > a[j] ) { temp = a[i] ; a[i] = a[j] ; a[j] = temp ; } if ( b[i] > b[j] ) { temp = b[i] ; b[i] = b[j] ; b[j] = temp ; } } } for ( i = j = k = 0 ; i <= 9 ; ) { if ( a[j] <= b[k] )

c[i++] = a[j++] ; else c[i++] = b[k++] ; if ( j == 5 || k == 5 ) break ; } for ( ; j <= 4 ; ) c[i++] = a[j++] ; for ( ; k <= 4 ; ) c[i++] = b[k++] ; printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 9 ; i++ ) printf ( "%d\t", c[i] ) ; getch( ) ; } /* CH9PR11.C: External Sorting. */ #include <stdio.h> #include <conio.h> #include <stdlib.h> void shownums ( char * ) ; void split ( char * ) ; void sort ( char * ) ; void main( ) { char str[67] ; clrscr( ) ; printf ( "Enter file name: " ) ; scanf ( "%s", str ) ; printf ( "Numbers before sorting:\n" ) ; shownums ( str ) ; split ( str ) ; sort ( str ) ;

printf ( "\nNumbers after sorting:\n" ) ; shownums ( str ) ; getch( ) ; } /* Displays the contents of file */ void shownums ( char *p ) { FILE *fp ; int i ; fp = fopen ( p, "rb" ) ; if ( fp == NULL ) { printf ( "Unable to open file." ) ; getch( ) ; exit ( 0 ) ; } while ( fread ( &i, sizeof ( int ), 1, fp ) != 0 ) printf ( "%d \t", i ) ; fclose ( fp ) ; } /* Splits the original file into two files */ void split ( char *p ) { FILE *fs, *ft ; long int l, count ; int i ; fs = fopen ( p, "rb" ) ; if ( fs == NULL ) { printf ( "Unable to open file." ) ; getch( ) ; exit ( 0 ) ; } ft = fopen ( "temp1.dat", "wb" ) ; if ( ft == NULL ) { fclose ( fs ) ; printf ( "Unable to open file." ) ;

getch( ) ; exit ( 1 ) ; } fseek ( fs, 0L, SEEK_END ) ; l = ftell ( fs ) ; fseek ( fs, 0L, SEEK_SET ) ; l = l / ( sizeof ( int ) * 2 ) ; for ( count = 1 ; count <= l ; count++ ) { fread ( &i, sizeof ( int ), 1, fs ) ; fwrite ( &i, sizeof ( int ), 1, ft ) ; } fclose ( ft ) ; ft = fopen ( "temp2.dat", "wb" ) ; if ( ft == NULL ) { fclose ( fs ) ; printf ( "Unable to open file." ) ; getch( ) ; exit ( 2 ) ; } while ( fread ( &i, sizeof ( int ), 1, fs ) != 0 ) fwrite ( &i, sizeof ( int ), 1, ft ) ; fcloseall ( ) ; } /* Sorts the file */ void sort ( char *p ) { FILE *fp[4] ; char *fnames[ ] = { "temp1.dat", "temp2.dat", "final1.dat", "final2.dat" }; int i, j = 1, i1, i2, flag1, flag2, p1, p2 ;

long int l ; while ( 1 ) { for ( i = 0 ; i <= 1 ; i++ ) { fp[i] = fopen ( fnames[i], "rb+" ) ; if ( fp[i] == NULL ) { fcloseall( ) ; printf ( "Unable to open file." ) ; getch( ) ; exit ( i ) ; } fseek ( fp[i], 0L, SEEK_END ) ; l = ftell ( fp[i] ) ; if ( l == 0 ) goto out ; fseek ( fp[i], 0L, SEEK_SET ) ; } for ( i = 2 ; i <= 3 ; i++ ) { fp[i] = fopen ( fnames[i], "wb" ) ; if ( fp[i] == NULL ) { fcloseall( ) ; printf ( "Unable to open file." ) ; getch( ) ; exit ( i ) ; } } i=2; i1 = i2 = 0 ; flag1 = flag2 = 1 ; while ( 1 ) { if ( flag1 ) { if ( fread ( &p1, sizeof ( int ), 1, fp[0] ) == 0 ) { /* If first file ends then the whole content of second file is written in the respective target file */

while ( fread ( &p2, sizeof ( int ), 1, fp[1] ) != 0 ) fwrite ( &p2, sizeof ( int ), 1, fp[i] ) ; break ; } } if ( flag2 ) { if ( fread ( &p2, sizeof ( int ), 1, fp[1] ) == 0 ) { /* If second file ends then the whole content of first file is written in the respective target file */ fwrite ( &p1, sizeof ( int ), 1, fp[i] ) ; while ( fread ( &p1, sizeof ( int ), 1, fp[0] ) != 0 ) fwrite ( &p1, sizeof ( int ), 1, fp[i] ) ; break ; } } if ( p1 < p2 ) { flag2 = 0 ; flag1 = 1 ; fwrite ( &p1, sizeof ( int ), 1, fp[i] ) ; i1++ ; } else { flag1 = 0 ; flag2 = 1 ; fwrite ( &p2, sizeof ( int ), 1, fp[i] ) ; i2++ ; } if ( i1 == j ) { flag1 = flag2 = 1 ; fwrite ( &p2, sizeof ( int ), 1, fp[i] ) ; for ( i2++ ; i2 < j ; i2++ ) { if ( fread ( &p2, sizeof ( int ), 1, fp[1] ) != 0 ) fwrite ( &p2, sizeof ( int ), 1, fp[i] ) ; } i1 = i2 = 0 ; i == 2 ? ( i = 3 ) : ( i = 2 ) ; }

if ( i2 == j ) { flag1 = flag2 = 1 ; fwrite ( &p1, sizeof ( int ), 1, fp[i] ) ; for ( i1++ ; i1 < j ; i1++ ) { if ( fread ( &p1, sizeof ( int ), 1, fp[0] ) != 0 ) fwrite ( &p1, sizeof ( int ), 1, fp[i] ) ; } i1 = i2 = 0 ; i == 2 ? ( i = 3 ) : ( i = 2 ) ; } } fcloseall( ) ; remove ( fnames[0] ) ; remove ( fnames[1] ) ; rename ( fnames[2], fnames[0] ) ; rename ( fnames[3], fnames[1] ) ; j *= 2 ; } out : fcloseall( ) ; remove ( p ) ; rename ( fnames[0], p ) ; remove ( fnames[1] ) ; } /* Program that creates random numbers in a given file. */ #include <stdio.h> #include <conio.h> #include <stdlib.h> void main( ) { FILE *fp ; char str [ 67 ] ; int i, noofr, j ; clrscr( ) ; printf ( "Enter file name: " ) ;

scanf ( "%s", str ) ; printf ( "Enter number of records: " ) ; scanf ( "%d", &noofr ) ; fp = fopen ( str, "wb" ) ; if ( fp == NULL ) { printf ( "Unable to create file." ) ; getch( ) ; exit ( 0 ) ; } randomize( ) ; for ( i = 0 ; i < noofr ; i++ ) { j = random ( 1000 ) ; fwrite ( &j, sizeof ( int ), 1, fp ) ; printf ( "%d\t", j ) ; } fclose ( fp ) ; printf ( "\nFile is created. \nPress any key to continue." ) ; getch( ) ; } /* CH10PR1.C: Program that implements depth first search algorithm. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define TRUE 1 #define FALSE 0 #define MAX 8 struct node { int data ; struct node *next ; }; int visited[MAX] ;

void dfs ( int, struct node ** ) ; struct node * getnode_write ( int ) ; void del ( struct node * ) ; void main( ) { struct node *arr[MAX] ; struct node *v1, *v2, *v3, *v4 ; int i ; clrscr( ) ; v1 = getnode_write ( 2 ) ; arr[0] = v1 ; v1 -> next = v2 = getnode_write ( 3 ) ; v2 -> next = NULL ; v1 = getnode_write ( 1 ) ; arr[1] = v1 ; v1 -> next = v2 = getnode_write ( 4 ) ; v2 -> next = v3 = getnode_write ( 5 ) ; v3 -> next = NULL ; v1 = getnode_write ( 1 ) ; arr[2] = v1 ; v1 -> next = v2 = getnode_write ( 6 ) ; v2 -> next = v3 = getnode_write ( 7 ) ; v3 -> next = NULL ; v1 = getnode_write ( 2 ) ; arr[3] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 2 ) ; arr[4] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 3 ) ; arr[5] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 3 ) ;

arr[6] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 4 ) ; arr[7] = v1 ; v1 -> next = v2 = getnode_write ( 5 ) ; v2 -> next = v3 = getnode_write ( 6 ) ; v3 -> next = v4 = getnode_write ( 7 ) ; v4 -> next = NULL ; dfs ( 1, arr ) ; for ( i = 0 ; i < MAX ; i++ ) del ( arr[i] ) ; getch( ) ; } void dfs ( int v, struct node **p ) { struct node *q ; visited[v - 1] = TRUE ; printf ( "%d\t", v ) ; q=*(p+v-1); while ( q != NULL ) { if ( visited[q -> data - 1] == FALSE ) dfs ( q -> data, p ) ; else q = q -> next ; } } struct node * getnode_write ( int val ) { struct node *newnode ; newnode = ( struct node * ) malloc ( sizeof ( struct node ) ) ; newnode -> data = val ; return newnode ; } void del ( struct node *n )

{ struct node *temp ; while ( n != NULL ) { temp = n -> next ; free ( n ) ; n = temp ; } } /* CH10PR2.C: Program that implements breadth first search algorithm. */ #include <stdio.h> #include <conio.h> #include <alloc.h> #define TRUE 1 #define FALSE 0 #define MAX 8 struct node { int data ; struct node *next ; }; int visited[MAX] ; int q[8] ; int front, rear ; void bfs ( int, struct node ** ) ; struct node * getnode_write ( int ) ; void addqueue ( int ) ; int deletequeue( ) ; int isempty( ) ; void del ( struct node * ) ; void main( ) { struct node *arr[MAX] ; struct node *v1, *v2, *v3, *v4 ; int i ; clrscr( ) ;

v1 = getnode_write ( 2 ) ; arr[0] = v1 ; v1 -> next = v2 = getnode_write ( 3 ) ; v2 -> next = NULL ; v1 = getnode_write ( 1 ) ; arr[1] = v1 ; v1 -> next = v2 = getnode_write ( 4 ) ; v2 -> next = v3 = getnode_write ( 5 ) ; v3 -> next = NULL ; v1 = getnode_write ( 1 ) ; arr[2] = v1 ; v1 -> next = v2 = getnode_write ( 6 ) ; v2 -> next = v3 = getnode_write ( 7 ) ; v3 -> next = NULL ; v1 = getnode_write ( 2 ) ; arr[3] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 2 ) ; arr[4] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 3 ) ; arr[5] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 3 ) ; arr[6] = v1 ; v1 -> next = v2 = getnode_write ( 8 ) ; v2 -> next = NULL ; v1 = getnode_write ( 4 ) ; arr[7] = v1 ; v1 -> next = v2 = getnode_write ( 5 ) ; v2 -> next = v3 = getnode_write ( 6 ) ; v3 -> next = v4 = getnode_write ( 7 ) ; v4 -> next = NULL ; front = rear = -1 ; bfs ( 1, arr ) ;

for ( i = 0 ; i < MAX ; i++ ) del ( arr[i] ) ; getch( ) ; } void bfs ( int v, struct node **p ) { struct node *u ; visited[v - 1] = TRUE ; printf ( "%d\t", v ) ; addqueue ( v ) ; while ( isempty( ) == FALSE ) { v = deletequeue( ) ; u=*(p+v-1); while ( u != NULL ) { if ( visited [ u -> data - 1 ] == FALSE ) { addqueue ( u -> data ) ; visited [ u -> data - 1 ] = TRUE ; printf ( "%d\t", u -> data ) ; } u = u -> next ; } } } struct node * getnode_write ( int val ) { struct node *newnode ; newnode = ( struct node * ) malloc ( sizeof ( struct node ) ) ; newnode -> data = val ; return newnode ; } void addqueue ( int vertex ) { if ( rear == MAX - 1 ) { printf ( "\nQueue Overflow." ) ;

exit( ) ; } rear++ ; q[rear] = vertex ; if ( front == -1 ) front = 0 ; } int deletequeue( ) { int data ; if ( front == -1 ) { printf ( "\nQueue Underflow." ) ; exit( ) ; } data = q[front] ; if ( front == rear ) front = rear = -1 ; else front++ ; return data ; } int isempty( ) { if ( front == -1 ) return TRUE ; return FALSE ; } void del ( struct node *n ) { struct node *temp ; while ( n != NULL ) { temp = n -> next ; free ( n ) ; n = temp ;

} } /* CH10PR3.C: Program to find the minimum cost of a spanning tree. */ #include <stdio.h> #include <conio.h> #include <alloc.h> struct lledge { int v1, v2 ; float cost ; struct lledge *next ; }; int stree[5] ; int count[5] ; int mincost ; struct lledge * kminstree ( struct lledge *, int ) ; int getrval ( int ) ; void combine ( int, int ) ; void del ( struct lledge * ) ; void main( ) { struct lledge *temp, *root ; int i ; clrscr( ) ; root = ( struct lledge * ) malloc ( sizeof ( struct lledge ) ) ; root -> v1 = 4 ; root -> v2 = 3 ; root -> cost = 1 ; temp = root -> next = ( struct lledge * ) malloc ( sizeof ( struct lledge ) ) ; temp -> v1 = 4 ; temp -> v2 = 2 ; temp -> cost = 2 ; temp -> next = ( struct lledge * ) malloc ( sizeof ( struct lledge ) ) ; temp = temp -> next ; temp -> v1 = 3 ;

temp -> v2 = 2 ; temp -> cost = 3 ; temp -> next = ( struct lledge * ) malloc ( sizeof ( struct lledge ) ) ; temp = temp -> next ; temp -> v1 = 4 ; temp -> v2 = 1 ; temp -> cost = 4 ; temp -> next = NULL ; root = kminstree ( root, 5 ) ; for ( i = 1 ; i <= 4 ; i++ ) printf ( "\nstree[%d] -> %d", i, stree[i] ) ; printf ( "\nThe minimum cost of spanning tree is %d", mincost ) ; del ( root ) ; getch( ) ; } struct lledge * kminstree ( struct lledge *root, int n ) { struct lledge *temp = NULL ; struct lledge *p, *q ; int noofedges = 0 ; int i, p1, p2 ; for ( i = 0 ; i < n ; i++ ) stree[i] = i ; for ( i = 0 ; i < n ; i++ ) count[i] = 0 ; while ( ( noofedges < ( n - 1 ) ) && ( root != NULL ) ) { p = root ; root = root -> next ; p1 = getrval ( p -> v1 ) ; p2 = getrval ( p -> v2 ) ; if ( p1 != p2 ) { combine ( p -> v1, p -> v2 ) ; noofedges++ ; mincost += p -> cost ; if ( temp == NULL )

{ temp = p ; q = temp ; } else { q -> next = p ; q = q -> next ; } q -> next = NULL ; } } return temp ; } int getrval ( int i ) { int j, k, temp ; k=i; while ( stree[k] != k ) k = stree[k] ; j=i; while ( j != k ) { temp = stree[j] ; stree[j] = k ; j = temp ; } return k ; } void combine ( int i, int j ) { if ( count[i] < count[j] ) stree[i] = j ; else { stree[j] = i ; if ( count[i] == count[j] ) count[j]++ ; } } void del ( struct lledge *root ) { struct lledge *temp ;

while ( root != NULL ) { temp = root -> next ; free ( root ) ; root = temp ; } } /* CH10PR4.C: Program to find the shortes path. */ #include <stdio.h> #include <conio.h> #define INF 9999 void main( ) { int arr[4][4] ; int cost[4][4] = { 7, 5, 0, 0, 7, 0, 0, 2, 0, 3, 0, 0, 4, 0, 1, 0 }; int i, j, k, n = 4 ; clrscr( ) ; for ( i = 0 ; i < n ; i++ ) { for ( j = 0; j < n ; j++ ) { if ( cost[i][j] == 0 ) arr[i][j] = INF ; else arr[i][j] = cost[i][j] ; } } printf ( "Adjacency matrix of cost of edges:\n" ) ; for ( i = 0 ; i < n ; i++ ) { for ( j = 0; j < n ; j++ ) printf ( "%d\t", arr[i][j] ) ; printf ( "\n" ) ;

} for ( k = 0 ; k < n ; k++ ) { for ( i = 0 ; i < n ; i++ ) { for ( j = 0 ; j < n ; j++ ) { if ( arr[i][j] > arr[i][k] + arr[k][j] ) arr[i][j] = arr[i][k] + arr[k][j]; } } } printf ( "\nAdjacency matrix of lowest cost between the vertices:\n" ) ; for ( i = 0 ; i < n ; i++ ) { for ( j = 0; j < n ; j++ ) printf ( "%d\t", arr[i][j] ) ; printf ( "\n" ) ; } getch( ) ; }

You might also like