1. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 1 of 47 DS Lab Programs
DATA STRUCTURES LABORATORY
[ 15CSL38 ]
DEPARTMENT OF INFORMATION SCIENCE
AND ENGINEERING
--------------------
HKBK COLLEGE OF ENGINEERING
Bengaluru - 560045
by:
Prof. A.Syed Mustafa
5. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 5 of 47 DS Lab Programs
1. Design, Develop and Implement a menu driven Program in C for the following Array
operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position(POS)
e. Exit.
Support the program with functions for each of the above operations.
1. #include<stdio.h>
2. #include<conio.h>
3. int a[100],n,i;
4.
5. /*create array with n elements*/
6. void createarray( )
7. {
8. printf("Enter the total no. of elementsn");
9. scanf("%d",&n);
10. printf("Enter the Elementsn");
11. for(i=0;i<n;i++)
12. scanf("%d",&a[i]);
13. }
14.
15. /* display all array elements*/
16. void displayarray( )
17. {
18. printf("The Elements in the array are:n");
19. for(i=0;i<n;i++)
20. printf("%dt",a[i]);
21. }
22.
23. /*insert the element at given position*/
24. void insertelement( )
25. {
26. int pos,elem;
27. printf("Enter the position of the element to be insertedn");
28. scanf("%d",&pos);
29. if(pos<1 || pos>n)
30. printf("Invalid Positonn");
31. else
32. {
33. printf("enter the element to be insertedn");
34. scanf("%d",&elem);
35. for (i = n; i >= pos; i--) /* shift elements left to right*/
36. a[i]=a[i-1];
37. a[i]=elem;
38. n++;/* total no. of elements in array increased by 1*/
39. }
40. }
41.
6. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 6 of 47 DS Lab Programs
42. /*remove the element at given position*/
43. void deleteelement( )
44. {
45. int pos;
46. printf("Enter the position of the element to be deletedn");
47. scanf("%d",&pos);
48. if(pos<1 || pos>n)
49. printf("Invalid Positonn");
50. else
51. {
52. printf("The element deleted is %dn",a[pos-1]);
53. for(i=pos;i<n;i++)/* shift elements right to left*/
54. a[i-1]=a[i];
55. n--;/* total no. of elements in array decreased by 1*/
56. }
57. }
58. void main( )
59. {
60. int ch;
61. clrscr( );
62. while(1)
63. {
64. printf("n1.Create Arrayn2.Display Arrayn3.Insert Elementn”);
65. printf(“4.Delete an Elementn5.Exitn");
66. printf("please enter the choicen");
67. scanf("%d",&ch);
68. switch(ch)
69. {
70. case 1: createarray( );
71. break;
72. case 2: displayarray( );
73. break;
74. case 3:insertelement( );
75. break;
76. case 4:deleteelement( );
77. break;
78. case 5: exit(0);
79. default: printf("Invalid Choicen");
80. }/*end switch*/
81. }/*end while*/
82.
83. } /*end main*/
7. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 7 of 47 DS Lab Programs
OUTPUT:
8. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 8 of 47 DS Lab Programs
2. Design, Develop and Implement a Program in C for the following operations on Strings
a. Read a main String (STR), a Pattern String (PAT) and a Replace String(REP)
b. Perform Pattern Matching Operation:
Find and Replace all occurrences of PAT in STR with REP if PAT exists in STR.
Report suitable messages in case PAT does not exist in STR
Support the program with functions for each of the above operations. Don't use Built-in
functions.
1. #include<stdio.h>
2. #include<conio.h>
3.
4.
5. /*reading input string*/
6. void readstr(char s[ ])
7. {
8. int i=-1;
9. do
10. {
11. s[++i]=getchar( );
12. }while(s[i]!='n');
13. s[i]=0;
14. }/*end readstr*/
15.
16. /*shifting right or left-shrinking or expanding */
17. void shift(char str[], int s, int slen, int rlen)
18. {
19. int i,len, nocs;
20. for(i=0;str[i]!=0;i++);
21. len=i;
22.
23.
24. if (rlen>slen)
25. {
26. /*if replacement string is having more characters than searching string */
27. nocs = rlen - slen; /* no. of characters to be shifted*/
28. for (i = len; i >= s + slen; i--) /* shift left to right */
29. str[i+nocs]=str[i];
30. }/*end if*/
31. else
32. {
33. /*if replacement string is having less characters than searching string */
34. nocs=slen-rlen; /* no. of characters to be shifted*/
35. for(i=s+rlen;i<=len-nocs;i++)/* shift right to left */
36. str[i]=str[i+nocs];
37. }/*end else*/
38.
39. }/*end shift*/
9. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 9 of 47 DS Lab Programs
40. /* find the search string and replace */
41. int findandrep(char str[], char ser[ ], char rep[ ])
42. {
43. int i,j,slen,rlen,k,count=0,pos;
44.
45. for (i = 0; ser[i] != 0; i++); /*find length of search string*/
46. slen=i;
47.
48. for(i=0;rep[i]!=0;i++); /*find length of replacement string*/
49. rlen=i;
50.
51. for(i=0;str[i]!=0;i++)
52. {
53. k=0;
54.
55. for (j = i; j<i + slen; j++) /* check each character*/
56. {
57. if (str[j] != ser[k]) /* if character not matches*/
58. break;
59. k++;
60. }/*end for j*/
61.
62. if (ser[k] == 0) /* if search last char is null,reached end- all chars matched*/
63. {
64. pos = i; /*starting position of searching string */
65. count++; /* count occurance of string*/
66. if (rlen != slen) /* if length of search and replace string not equal*/
67. shift(str,pos,slen,rlen);
68.
69. for (j = 0; j<rlen; j++) /* replace the string*/
70. str[pos+j]=rep[j];
71. i = pos + rlen; /* goto next position to search the string after replacement*/
72. }/*end if */
73.
74. }/*end for i*/
75.
76. return(count);
77.
78. }/*end findandrep*/
79.
80.
81. void main( )
82. {
83. char str[100],pat[100],rep[100];
84. int count;
85. clrscr( );
86. printf("Enter the stringn");
87. readstr(str);
88. printf("enter the string to be foundn");
89. readstr(pat);
10. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 10 of 47 DS Lab Programs
90. printf("Enter the string to be replacedn");
91. readstr(rep);
92. count=findandrep(str,pat,rep);
93. if(count)
94. printf("no. of occurances: %dnThe final string is: %sn",count,str);
95. else
96. printf("String is not foundn");
97. getch( );
98. }/*end main*/
OUTPUT:
11. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 11 of 47 DS Lab Programs
3. Design, Develop and Implement a menu driven Program in C for the following
operations on STACK of Integers (Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the above operations
1. #include<stdio.h>
2. #include<conio.h>
3. int tos=-1,max,a[100];
4.
5. /*insert the element into the stack*/
6. void push(int elem)
7. {
8. if(tos = = max-1)
9. printf("Stack Overflown");
10. else
11. a[++tos]=elem;
12. } /* end push*/
13.
14. /* remove the element from the stack*/
15. int pop( )
16. {
17. return(a[tos--]);
18. } /* end pop*/
19.
20.
21. /*display the content of the stack*/
22. void display( )
23. {
24. int i;
25. if(tos<0)
26. printf("Stack is emptyn");
27. else
28. for(i=tos;i>=0;i--)
29. printf("%dt",a[i]);
30. }/*end display*/
31.
32. /*find the given no. is palindrome or not*/
33. void palindrome( )
34. {
35. int n,no,d,p=1;
36. tos=-1;
37. max = 5; /* till 5 digit no. 32767 or 65536 - max int value, size of stack-5 */
38. printf("enter the number to check palindromen");
39. scanf("%d",&n);
40. no=n;
12. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 12 of 47 DS Lab Programs
41. while (no != 0) /* extract each digit and push into stack*/
42. {
43. d=no%10;
44. push(d);
45. no=no/10;
46. }/*end while*/
47.
48. no=n;
49. while(no!=0)/* extract each digit*/
50. {
51. d=no%10;
52. if(d!=pop()) /* compare with top of stack */
53. {
54. /*if first digit in tos and last digit from no. does not match and so on.*/
55. p=0;
56. break;
57. }/*end if*/
58. no=no/10;
59. }/*end while*/
60.
61. if(p)
62. printf("%d is a palindromen",n);
63. else
64. printf("%d is not a plaindromen",n);
65. } /* end palindrome*/
66.
67.
68. void main( )
69. {
70. int ch,elem;
71. clrscr();
72. printf("Enter the maximum size of the stackn");
73. scanf("%d",&max);
74. while(1)
75. {
76. printf("nStackn1.Pushn2.Popn3.Palindromen4.Displayn5.Exitn");
77. printf("Enter the Choicen");
78. scanf("%d",&ch);
79. switch(ch)
80. {
81. case 1: printf("Enter the element to be pushedn");
82. scanf("%d",&elem);
83. push(elem);
84. break;
85. case 2: if(tos<0)
86. printf("Stack Underflown");
87. else
88. {
89. elem=pop( );
90. printf("The popped Element is %dn",elem);
13. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 13 of 47 DS Lab Programs
91. }/*end else*/
92. break;
93.
94. case 3:palindrome( );
95. break;
96.
97. case 4: display( );
98. break;
99. case 5: exit(0);
100. default: printf("Invalid Choicen");
101. } /* end switch*/
102. } /* end while*/
103. } /*end main*/
OUTPUT:
14. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 14 of 47 DS Lab Programs
4. Design, Develop and Implement a Program in C for converting an Infix Expression to Postfix
Expression. Program should support for both parenthesized and free parenthesized expressions
with the operators: +, -, *, /, %(Remainder), ^(Power) and alphanumeric operands.
1. #define SIZE 50 /* Size of Stack */
2. #include <ctype.h>
3. char s[SIZE];
4. int top = -1; /* Global declarations */
5. /* Function for PUSH operation */
6. void push(char item)
7. { s[++top] = item;
8. }/*end push*/
9.
10. /* Function for POP operation */
11. char pop( )
12. {
13. return (s[top--]);
14. }/*end pop*/
15.
16. /* Function for finding precedence */
17. int pr(char ch)
18. {
19. switch (ch)
20. {
21. case '(': return 1;
22. case '+':
23. case '-': return 2;
24. case '*':
25. case '/':
26. case '%': return 3;
27. case '^': return 4;
28. }/*end switch*/
29. }/*end pr*/
30.
31. /*convert infix expression to postfix*/
32. void infixtopostfix(char infix[],char postfix[])
33. {
34. int i,k=0;
35. char ch;
36. for(i=0;infix[i]!=0;i++)
37. {
38. ch = infix[i];/* extract each char*/
39. if ( ch == '(' )/* if char is open bracket*/
40. push(ch);
41. else if (isalnum(ch))/* if char is alphabet or digit*/
42. postfix[k++] = ch;
43. else if (ch == ')' )/* if char is closing bracket*/
44. {
15. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 15 of 47 DS Lab Programs
45. while (s[top] != '(' ) /* remove all chars from stack till open bracket in stack*/
46. postfix[k++] = pop( );
47. pop( ); /* Remove ( */
48. }/*end elseif*/
49. else
50. { /* if char is Operator */
51. while (top!=-1 && pr(s[top]) >= pr(ch) && ch!='^')
52. postfix[k++] = pop();
53. push(ch);
54. } /*end if*/
55. } /*end for*/
56.
57. while (top != -1) /* Pop from stack till empty */
58. postfix[k++] = pop( );
59.
60. postfix[k] = '0'; /* Make postfix as valid string by inserting null at last character*/
61. }/* end postfix*/
62.
63. void main( )
64. { /* Main Program */
65. char infix[50], postfix[50];
66. clrscr();
67. printf("nnEnter the Infix Expression n ");
68. scanf("%s", infix);
69. infixtopostfix(infix,postfix);
70. printf("nnGiven Infix Expression is: %sn",infix);
71. printf("Postfix Expression is: %sn",postfix);
72. getch();
73. }/*end main*/
OUTPUT:
16. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 16 of 47 DS Lab Programs
5. Design, Develop and Implement a Program in C for the following Stack Applications:
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks.
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
1. #define SIZE 50 /* Size of Stack */
2. #include <stdio.h>
3. #include<conio.h>
4. #include<math.h>
5. int s[SIZE];
6. int top=-1; /* Global declarations */
7.
8. void push(int elem) /* Function for PUSH operation */
9. {
10. s[++top]=elem;
11. } /* end of push */
12.
13. int pop( ) /* Function for POP operation */
14. {
15. return(s[top--]);
16. } /* end of pop */
17.
18. int eval_post(char postfix[ ]) /* evaluating postfix expression*/
19. {
20. int i,a,b;
21. char ch;
22. for(i=0;postfix[i]!=0;i++)
23. {
24. ch=postfix[i];
25. if(ch<='9' && ch>='0') /* if digit, push it to stack*/
26. push(ch-'0');
27. else /* if it is operator*/
28. {
29. b = pop( );/* top of stack is first no*/
30. a=pop( );/* next top of stack is second no*/
31. switch(ch)
32. {
33. case '+': push(a+b);
34. break;
35. case '-': push(a-b);
36. break;
37. case '*': push(a*b);
38. break;
39. case '/': push(a/b);
40. break;
41. case '%': push(a%b);
42. break;
43. case '^': push(pow(a,b));
17. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 17 of 47 DS Lab Programs
44. break;
45. }/*end switch*/
46. } /*end else- if*/
47. }/*end for*/
48. return pop( ); /*return last char from stack*/
49. }/*end eval_post*/
50.
51. void main( ) /* Main Program */
52. {
53. char postfix[50];
54. int result;
55. clrscr( );
56. printf("Enter the Valid Postfix Expressionn");
57. scanf("%s",postfix);
58. result=eval_post(postfix);
59. printf("n Given Postfix Expression: %sn",postfix);
60. printf("n Result after Evaluation: %dn",result);
61. getch( );
62. } /* end of main */
OUTPUT:
18. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 18 of 47 DS Lab Programs
b. Solving Tower of Hanoi problem with n disks.
1. #include<stdio.h>
2. #include<conio.h>
3.
4. /* C recursive function to solve tower of hanoi */
5. void TowerOfHanoi(int n, char source, char dest, char inter)
6. {
7. if (n == 1)
8. printf("n Move disk 1 from rod %c to rod %c", source, dest);
9. else
10. {
11. /* from source to intermediate through destination*/
12. TowerOfHanoi(n - 1, source, inter, dest);
13. printf("n Move disk %d from rod %c to rod %c", n, source, dest);
14. /* from intermediate to destination through source */
15. TowerOfHanoi(n - 1,inter, dest, source);
16. }/*end if*/
17. }/*end TowerofHanoi*/
18.
19. void main( )
20. {
21. int n;
22. clrscr( );
23. printf("Enter total no of disksn");
24. scanf("%d",&n);
25. TowerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
26. getch( );
27. }/*end main*/
OUTPUT:
19. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 19 of 47 DS Lab Programs
6. Design, Develop and Implement a menu driven Program in C for the following operations on
Circular QUEUE of Characters (Array Implementation of Queue with maximum size MAX):
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations.
1. #include<stdio.h>
2. #include<conio.h>
3. int max,count=0,f=0,r = -1;
4. char a[100],elem;
5.
6. /*insert element into circular queue*/
7. void InsertQ( )
8. {
9. if(count==max)
10. printf("Queue is Fulln");
11. else
12. {
13. printf("Enter the element to be insertedn");
14. fflush(stdin);
15. elem=getchar();
16. r = (r + 1) % max; /* if rear end reached the max size of Queue, go to begining*/
17. a[r]=elem;
18. count++;/* count of element in the queue incremented*/
19. }/*end else*/
20. } /* end insert*/
21.
22. /*Remove the element from circular Queue*/
23. void DeleteQ( )
24. {
25. if(count = = 0)
26. printf("Queue is Emptyn");
27. else
28. {
29. elem=a[f];
30. f=(f+1)%max;/* if front end reached the max size of Queue, go to begining*/
31. printf("Element deleted is %cn",elem);
32. count--;/* count of element in the queue decremented*/
33. }/*end else*/
34. } /*end Delete*/
35.
36. /* Display the content of circular queue*/
37. void DisplayQ( )
38. {
39. int i;
40. if(count = = 0)
41. printf("Queue is Emptyn");
20. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 20 of 47 DS Lab Programs
42. else
43. {
44. printf("The elements in the Queue aren:");
45. for(i=0;i<count;i++)
46. printf("%ct",a[(f+i)%max]);/*if front end reached the max size of Queue,go to begining*/
47. }/*end else*/
48. }/*end display*/
49.
50. void main()
51. {
52. int ch;
53. clrscr();
54. printf("Enter the maximum size of the circular QUEUEn");
55. scanf("%d",&max);
56. while(1)
57. {
58. printf("nCicular QUEUEn1.Insertn2.Deleten3.Displayn4.Exitn");
59. printf("Enter the Choicen");
60. scanf("%d",&ch);
61. switch(ch)
62. {
63. case 1: InsertQ( );
64. break;
65. case 2: DeleteQ( );
66. break;
67. case 3: DisplayQ( );
68. break;
69. case 4: exit(0);
70. default: printf("Invalid Choicen");
71. } /* end switch*/
72. } /* end while*/
73. } /*end main*/
OUTPUT:
21. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 21 of 47 DS Lab Programs
7. Design, Develop and Implement a menu driven Program in C for the following operations on
Singly Linked List (SLL) of Student Data with the fields: USN,Name, Branch, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit
1. #include<stdio.h>
2. #include<conio.h>
3. #include<alloc.h>
4.
5. /*create structure to store student detail*/
6. struct student
7. {
8. char usn[12];
9. char name[25];
10. char branch[25];
11. int sem;
12. char phone_no[12];
13. struct student *link;
14. };
15.
16. typedef struct student STUD;
17.
18. /*to get student details from user*/
19. STUD *read_data()
20. {
21.
22. STUD *temp;
23.
24. temp = (STUD *)malloc(sizeof(STUD)); /*create a node which stores student's details*/
25. printf("Enter the Students Details:n");
26. printf("Enter USNn");
27. scanf("%s",temp->usn);
28. printf("Enter Namen");
29. scanf("%s",temp->name);
30. printf("Enter Branch n");
31. scanf("%s",temp->branch);
32. printf("Enter Semestern");
33. scanf("%d",&temp->sem);
34. printf("Enter Phone Numbern");
35. scanf("%s",temp->phone_no);
36.
37. temp->link = NULL;/*link part of node is assigned with null value*/
38.
39. return temp;
40. }/*end of read_data*/
22. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 22 of 47 DS Lab Programs
41. /*to insert the node in the begining of list*/
42. STUD * insert_front(STUD *first)
43. {
44. STUD *temp;
45. temp = read_data(); /* get new node which has student's detail*/
46. temp->link = first; /*assign the previous first node as link to the new node*/
47. return temp;/* retuen new node as first node*/
48. }/*end of insert_front*/
49.
50. /*to delete the node from the begining of list*/
51. STUD* Delete_front(STUD* first)
52. {
53. STUD* cur = first; /* assign first node as current node */
54. if (first == 0)/*if no first node*/
55. printf("List is Emptyn");
56. else
57. { /* if there are nodes*/
58. printf("Deleted Student's Details are:n");
59. printf("USNtNAMEtBRANCHtSEMtPHONE NO.n");/*display student's detail*/
60. printf("%st%st",first->usn,first->name);
61. printf("%st%dt%sn",first->branch,first->sem,first->phone_no);
62. first = first->link;/* make the first node as next node*/
63. free(cur);/* delete the previous first node*/
64. }/*end else*/
65. return(first);/*return the new-[next node] as first node*/
66. }/*end of Delete_front*/
67.
68. /*create single linked list*/
69. STUD * CreateSLL(STUD *first)
70. {
71. int n,i;
72. printf("Enter the total no. of studentsn");
73. scanf("%d",&n);
74. for(i=0;i<n;i++)/*for every student, create & insert the node into the front of the list*/
75. first = insert_front(first);
76. return(first);/*return the first node of the list*/
77. }/*end of CreateSLL*/
78.
79.
80. /*Display the details of all students by traversing all nodes from the singly linked list.*/
81. void DisplaySLL(STUD* first)
82. {
83. int count=0;
84. if(first==0)
85. printf("List is Emptyn");
86. else
87. {
88. printf("Students Details are:n");
89. printf("USNtNAMEtBRANCHtSEMtPHONE NO.n");
90.
23. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 23 of 47 DS Lab Programs
91. while (first != 0)/* as long as first[current] node is not null, not reached end of list*/
92. {
93. printf("%st%st",first->usn,first->name);
94. printf("%st%dt%sn",first->branch,first->sem,first->phone_no);
95. first = first->link;/* make next node as first[current] node*/
96. count++;
97. } /*end while*/
98. printf("The number of nodes in SLL=%dn",count);
99. }/*end of else*/
100. }/*end of DisplaySLL*/
101.
102. /*function to insert or delete a node in the front end of list*/
103. STUD* InsertDeleteFront(STUD* first)
104. {
105. int ch;
106. while(1)
107. {
108. printf("nStack Demon1.Insert at frontn2.Delete at Frontn3.Displayn4.Main Menu");
109. printf("Enter the Choicen");
110. scanf("%d",&ch);
111. switch(ch)
112. {
113. case 1: first=insert_front(first);
114. break;
115. case 2: first=Delete_front(first);
116. break;
117. case 3: DisplaySLL(first);
118. break;
119. case 4: return(first);
120.
121. default: printf("Invalid Choicen");
122. } /* end switch*/
123. }/* end while*/
124. }/*end of InsertDeleteFront*/
125.
126. /*to insert the node at the end of list*/
127. STUD* insert_End(STUD* first)
128. {
129. STUD *temp,*cur;
130. temp = read_data();/* get new node which has student's detail*/
131. if (first == 0)/*if no node*/
132. return(temp);/* return new node as first node*/
133. cur = first;/*assign first node as current node*/
134. /*as long as current node's link is not null,i.e till reaching last node*/
135. while (cur->link != 0)
136. cur = cur->link;/*assign next node as current node*/
137. cur->link = temp;/*last node's link is conneced to new node*/
138. return(first);/*return the first node*/
139. }/*end of insert_End*/
140.
24. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 24 of 47 DS Lab Programs
141. /*to delete the node from the end of list*/
142. STUD* Delete_End(STUD* first)
143. {
144. STUD *prev=0,*cur=first;
145. if(first==0)
146. printf("List is Emptyn");
147. else
148. {
149. while(cur->link!=0)/*as long as current node's link is not null,i.e till reaching last node*/
150. {
151. prev = cur;/*assign current node as previous node*/
152. cur = cur->link;/*assign next node as current node*/
153. }/*end while*/
154. printf("Deleted Student's Details are:n");
155. printf("USNtNAMEtBRANCHtSEMtPHONE NO.n");
156. printf("%st%st",cur->usn,cur->name);
157. printf("%st%dt%sn",cur->branch,cur->sem,cur->phone_no);
158. free(cur); /*remove the current node-i.e last node*/
159. if (first->link == 0)/*if there is only one node*/
160. first = 0; /*retrun null as there is no node availabe, [first node is deleted]*/
161. else
162. prev->link = 0;/*make previous node link as null*/
163. return(first);/*return the first node*/
164. }/* end else*/
165. }/*end deleteend*/
166.
167. /*to insert and remove the node from the end of list*/
168. STUD* InsertDeleteEnd(STUD* first)
169. {
170. int ch;
171. while(1)
172. {
173. printf("n1.Insert at Endn2.Delete at Endn3.Displayn4.Main Menu");
174. printf("Enter the Choicen");
175. scanf("%d",&ch);
176. switch(ch)
177. {
178. case 1: first=insert_End(first);
179. break;
180. case 2: first=Delete_End(first);
181. break;
182. case 3: DisplaySLL(first);
183. break;
184. case 4: return(first);
185.
186. default: printf("Invalid Choicen");
187. } /* end switch*/
188. }/* end while*/
189. }/*end InsertDeleteEnd*/
190.
25. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 25 of 47 DS Lab Programs
191. void main( )
192. {
193. int ch;
194. STUD *first=0;
195. clrscr();
196.
197. while(1)
198. {
199. printf("nSingly Linked Listn");
200. printf("1.Create a SLL of N Students Data by using front insertionn");
201. printf("2.Display the status of SLL and count the number of nodesn");
202. printf("3.Perform Insertion / Deletion at End of SLLn");
203. printf("4.Perform Insertion and Deletion at Front of SLLn");
204. printf("5.Exitn");
205. printf("Enter the Choicen");
206. scanf("%d",&ch);
207. switch(ch)
208. {
209. case 1: first=CreateSLL(first);
210. break;
211. case 2: DisplaySLL(first);
212. break;
213. case 3: first=InsertDeleteEnd(first);
214. break;
215. case 4: first=InsertDeleteFront(first);
216. break;
217. case 5: exit(0);
218. default: printf("Invalid Choicen");
219. } /* end switch*/
220. } /* end while*/
221. } /*end main*/
OUTPUT:
26. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 26 of 47 DS Lab Programs
8. Design, Develop and Implement a menu driven Program in C for the following operations on
Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation,
Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue
f. Exit
1. #include<stdio.h>
2. #include<conio.h>
3. #include<alloc.h>
4.
5. /*create structure to store Employee detail*/
6. struct emp
7. {
8. char ssn[12];
9. char name[50];
10. char dept[50];
11. char design[25];
12. long salary;
13. char phone_no[12];
14. struct node *llink;
15. struct node *rlink;
16. };
17.
18.
19. typedef struct emp EMP;
20.
21. /*function prototypes*/
22. EMP *read_data( );
23. EMP* insert_End(EMP* first);
24. EMP * CreateDLL(EMP *first);
25. void DisplayDLL(EMP* first);
26. EMP* Delete_End(EMP* first);
27. EMP* InsertDeleteEnd(EMP* first);
28. EMP* Dequeue(EMP* first);
29.
30. /*to get Employee details from user*/
31. EMP *read_data( )
32. {
33. /*create a node which stores employee's details*/
34. EMP *temp=(EMP*)malloc(sizeof(EMP));
35. printf("Enter the Employees Details:n");
36. printf("Enter SSNn");
37. scanf("%s",temp->ssn);
38. printf("Enter Namen");
39. scanf("%s",temp->name);
27. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 27 of 47 DS Lab Programs
40. printf("Enter Departmentn");
41. scanf("%s",temp->dept);
42. printf("Enter Designationn");
43. scanf("%s",temp->design);
44. printf("Enter Salaryn");
45. scanf("%ld",&temp->salary);
46. printf("Enter PhoneNumbern");
47. scanf("%s",temp->phone_no);
48. temp->rlink=temp->llink=NULL;/*link part of node is assigned with null value*/
49. return temp;
50. }/*end of read_data*/
51.
52. /*to insert the node at the end of list*/
53. EMP* insert_End(EMP* first)
54. {
55. EMP *temp,*cur;
56. temp=read_data( );/* get new node which has employee's detail*/
57. if(first==0)/*if no node*/
58. return(temp);/* return new node as first node*/
59. cur=first;/*assign first node as current node*/
60. /*as long as current node's link is not null,i.e till reaching last node*/
61. while(cur->rlink!=0)
62. cur=cur->rlink;/*assign next node as current node*/
63. cur->rlink=temp;/*last node's right link is conneced to new node*/
64. temp->llink = cur;/*new node's left link is connected to last node[current node]*/
65. return(first);/*return the first node*/
66. }/*end of insert_End*/
67.
68. /*create Double linked list*/
69. EMP * CreateDLL(EMP *first)
70. {
71. int n,i;
72. printf("Enter the total no. of EMPloyeesn");
73. scanf("%d",&n);
74. /*for every employee, create node and insert the node at the end of the list*/
75. for(i=0;i<n;i++)
76. first=insert_End(first);
77. return(first);/*return the first node of the list*/
78. }/*end of CreateDLL*/
79.
80.
81. /*Display the details of all Employees by traversing all nodes from the DLL.*/
82. void DisplayDLL(EMP* first)
83. {
84. int count=0;
85. if(first==0)
86. printf("List is Emptyn");
87. else
88. {
89. printf("nEMPloyees Details are:n");
28. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 28 of 47 DS Lab Programs
90. printf("SSNtNAMEtDEPARTMENTt");
91. printf("DESIGNATIONtSALARYnPHONE NO.n");
92. /* as long as first[current] node is not null, not reached end of list*/
93. while(first!=0)
94. {
95. printf("%st%st",first->ssn,first->name);
96. printf("%st%st",first->dept,first->design);
97. printf("%ldt%sn",first->salary,first->phone_no);
98. first=first->rlink;/* make next node as first[current] node*/
99. count++;
100. }/*end else*/
101. printf("The number of nodes in DLL=%dn",count);
102. }/*end of else*/
103. }/*end of DisplayDLL*/
104.
105. /*to delete the node from the end of list*/
106. EMP* Delete_End(EMP* first)
107. {
108. EMP *prev=0,*cur=first;
109. if(first==0)
110. printf("List is Emptyn");
111. else
112. {
113. /*as long as current node's right link is not null,i.e till reaching last node*/
114. while(cur->rlink!=0)
115. cur=cur->rlink;/*assign next node as current node*/
116. printf("nDeleted Employee Details are:n");
117. printf("SSNtNAMEtDEPARTMENTt");
118. printf("DESIGNATIONtSALARYnPHONE NO.n");
119. printf("%st%st",cur->ssn,cur->name);
120. printf("%st%st",cur->dept,cur->design);
121. printf("%ldt%sn",cur->salary,cur->phone_no);
122. if(first->rlink==0)/*if there is only one node*/
123. first=0;/*retrun null as there is no node availabe, [first node is deleted]*/
124. else
125. {
126. /*make previous node as current node[last nodel]'s left link i.e last but one node*/
127. prev=cur->llink;
128. prev->rlink=0;/*make previous node's right link as null*/
129. }
130. free(cur);/*remove the current node-i.e last node*/
131.
132. return(first);/*return the first node*/
133. }/* end else*/
134. }/*end deleteend*/
29. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 29 of 47 DS Lab Programs
135. /*to insert and remove the node from the end of list*/
136. EMP* InsertDeleteEnd(EMP* first)
137. {
138. int ch;
139. while(1)
140. {
141. printf("n1.Insert at Endn2.Delete at Endn3.Displayn4.Main Menu");
142. printf("Enter the Choicen");
143. scanf("%d",&ch);
144. switch(ch)
145. {
146. case 1: first=insert_End(first);
147. break;
148. case 2: first=Delete_End(first);
149. break;
150. case 3: DisplayDLL(first);
151. break;
152. case 4: return(first);
153.
154. default: printf("Invalid Choicen");
155. } /* end switch*/
156. }/* end while*/
157. }/*end InsertDeleteEnd*/
158.
159.
160. /*to insert the node in the begining of list*/
161. EMP *insert_front(EMP *first)
162. {
163. EMP *temp;
164. temp=read_data();/* get new node which has employee's detail*/
165. if(first!=0)
166. {
167. temp->rlink=first;/*assign the previous first node as right link to the new node*/
168. first->llink=temp;/*assign the previous first node's left link as new node*/
169. }
170. return temp;/*return the new-[next node] as first node*/
171. }/*end Insert_front*/
172.
173.
174. /*to delete the node from the begining of list*/
175. EMP* Delete_front(EMP* first)
176. {
177. EMP* cur=first;/* assign first node as current node */
178. if(first==0)/*if no first node*/
179. printf("List is Emptyn");
180. else
181. { /* if there are nodes*/
182. printf("nDeleted Employee Details are:n");
183. printf("SSNtNAMEtDEPARTMENTt");
30. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 30 of 47 DS Lab Programs
184. printf("DESIGNATIONtSALARYnPHONE NO.n");/*display emplyee's detail*/
185. printf("%st%st",cur->ssn,cur->name);
186. printf("%st%st",cur->dept,cur->design);
187. printf("%ldt%sn",cur->salary,cur->phone_no);
188. if(first->rlink==0)/*if there is only one node*/
189. first = 0; /*assign first node as null*/
190. else
191. {/*if there are nodes*/
192. first=first->rlink;/*assign next node as first node*/
193. first->llink = 0;/*assign new first node's left link as null*/
194. }
195. free(cur);/*remove the previous first[current] node*/
196. }/* end else*/
197. return(first);/*return the first node*/
198. }/*end Delete_front*/
199.
200.
201. /*to insert and remove the node from the begining of list*/
202. EMP* InsertDeleteFront(EMP* first)
203. {
204. int ch;
205. while(1)
206. {
207. printf("1.Insert at frontn2.Delete at Frontn3.Displayn4.Main Menu");
208. printf("Enter the Choicen");
209. scanf("%d",&ch);
210. switch(ch)
211. {
212. case 1: first=insert_front(first);
213. break;
214. case 2: first=Delete_front(first);
215. break;
216. case 3: DisplayDLL(first);
217. break;
218. case 4: return(first);
219.
220.
221. default: printf("Invalid Choicen");
222. } /* end switch*/
223. }/* end while*/
224. }/*end InsertDeleteFront*/
225.
226. /*to perform double ended queue*/
227. EMP* Dequeue(EMP* first)
228. {
229. int ch;
230. while(1)
231. {
232. printf("n1.Insert at frontn2.Delete at Frontn");
233. printf("n3.Insert at Endn4.Delete at Endn");
31. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 31 of 47 DS Lab Programs
234. printf("5.Displayn6.Main Menu");
235. printf("Enter the Choicen");
236. scanf("%d",&ch);
237. switch(ch)
238. {
239. case 1: first=insert_front(first);
240. break;
241. case 2: first=Delete_front(first);
242. break;
243. case 3: first=insert_End(first);
244. break;
245. case 4: first=Delete_End(first);
246. break;
247. case 5: DisplayDLL(first);
248. break;
249. case 6: return(first);
250. default: printf("Invalid Choicen");
251. } /* end switch*/
252. }/* end while*/
253. }/*end Dequeue*/
254.
255. void main( )
256. {
257. int ch;
258.
259. EMP *first=0;
260. clrscr ( );
261.
262. while(1)
263. {
264. printf("nDoubly Linked Listn");
265. printf("1.Create a DLL of N Employees Data by using end insertionn");
266. printf("2.Display the status of DLL and count the number of nodesn");
267. printf("3.Perform Insertion / Deletion at End of DLLn");
268. printf("4.Perform Insertion and Deletion at Front of DLLn");
269. printf("5.DLL as Double Ended Queuen");
270. printf("6.Exitn");
271. printf("Enter the Choicen");
272. scanf("%d",&ch);
273. switch(ch)
274. {
275. case 1: first=CreateDLL(first);
276. break;
277. case 2: DisplayDLL(first);
278. break;
279. case 3:first=InsertDeleteEnd(first);
280. break;
281. case 4: first=InsertDeleteFront(first);
282. break;
283. case 5: first=Dequeue(first);
32. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 32 of 47 DS Lab Programs
284. break;
285. case 6: exit(0);
286. default: printf("Invalid Choicen");
287. } /* end switch*/
288. } /* end while*/
289. } /*end main*/
OUTPUT:
33. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 33 of 47 DS Lab Programs
9. Design, Develop and Implement a Program in C for the following operations on Singly Circular
Linked List (SCLL) with header nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in
POLYSUM(x,y,z)
Support the program with appropriate functions for each of the above operations.
1. #include<stdio.h>
2. #include<conio.h>
3. #include<alloc.h>
4. #include<math.h>
5.
6. typedef struct
7. {
8. int coef, xexp, yexp, zexp;
9. struct poly *link;
10. }POLY;
11.
12. /*insert the polinomial term-node at the end of the list*/
13. void attach(POLY *poly1,int coef,int xexp,int yexp,int zexp)
14. {
15.
16. POLY *nnode, *cur;
17. nnode = (POLY*)malloc(sizeof(POLY));/*create new node for each polynomial term*/
18. nnode->coef = coef;/*assign coefficient value in the node*/
19. nnode->xexp = xexp;/*assign exponent value of x in the node*/
20. nnode->yexp = yexp;/*assign exponent value of y in the node*/
21. nnode->zexp = zexp;/*assign exponent value of z in the node*/
22.
23. cur = poly1->link;/*assign first node pointed by header node's link to current pointer*/
24. /*traverse as long as the node is not header node-till reaching last node*/
25. while (cur->link != poly1)
26. cur = cur->link; /*assign next node as current node*/
27.
28. cur->link = nnode;/*assign new node to link of last[current] node*/
29. nnode->link = poly1;/*link new node to header node-poly1*/
30.
31. }/* end of attach-insert at end */
32.
33.
34. /*creating a polinomial with many terms*/
35. void createpoly(POLY *poly1)
36. {
37. int n, i, coef, xexp, yexp, zexp;
38.
39. printf("Enter no of termsn");
40. scanf("%d", &n);
41. printf("enter the details of the ploynomialn");
34. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 34 of 47 DS Lab Programs
42. for (i = 1; i <= n; i++)
43. {
44. printf("Enter term - %d: Co-Efficient and Power of x,y & zn", i);
45. scanf("%d%d%d%d", &coef, &xexp, &yexp, &zexp);
46. /*create new node for each term and insert at end of the list*/
47. attach(poly1, coef, xexp, yexp, zexp);
48. }/*end for*/
49. }/*end createpoly */
50.
51.
52. /*Evaluate polynomial*/
53. void evaluatepoly(POLY *poly1)
54. {
55. POLY *cur;
56. int x, y, z, res = 0;
57. cur = poly1->link;/*first actual node-header's[poly1] link*/
58. printf("nEnter the values x, y and z:n");
59. scanf("%d%d%d", &x, &y, &z);
60. while (cur != poly1)/*till current node reaches the header node again*/
61. {
62. /*find the actual value by coeff*xterm*yterm*zterm */
63. res += cur->coef*pow(x, cur->xexp)*pow(y, cur->yexp)*pow(z, cur->zexp);
cur = cur->link;/*move to the next node-next term in the polynomial*/
64. }/*end while*/
65. printf("Evaluated Result of Polynomial = %dn", res);
66. }/*end evaluatepoly*/
67.
68. /*display the polynomial*/
69. void display(POLY *poly1)
70. {
71. POLY *cur=poly1->link;/*first actual node-header's[poly1] link*/
72. printf("%dx^%dy^%dz^%d", cur->coef, cur->xexp, cur->yexp, cur->zexp);
73. /*display first node */
74. cur = cur->link;/*assign next node*/
75. while (cur != poly1)/*till current node reaches the header node again*/
76. {
77. /*display next node with + symbol */
78. printf(" + %dx^%dy^%dz^%d", cur->coef, cur->xexp, cur->yexp, cur->zexp);
79. cur=cur->link;/*move to the next node-next term in the polynomial*/
80. } /* end while */
81. }/* end of display */
82.
83.
84. /*Represent and Evaluate a Polynomial P(x,y,z)*/
85. void repandevalpoly( )
86. {
87. POLY *poly1;
88.
89. poly1 = (POLY*)malloc(sizeof(POLY));/*create header node for the polynomial*/
90. poly1->link = poly1;/*link the header node to itself*/
35. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 35 of 47 DS Lab Programs
91.
92. createpoly(poly1); /*creating a polinomial with many terms*/
93. display(poly1);/*display the polynomial*/
94. evaluatepoly(poly1);/*Evaluate the polynomial*/
95. }/* end of repandevalpoly*/
96.
97.
98. /*Add or sum 2 polynomials and result in third polynomial */
99. void addpoly(POLY *poly1,POLY *poly2,POLY *polysum)
100. {
101. int comp;
102. POLY *a,*b;
103. a = poly1->link;/*first node of first polynomial*/
104. b=poly2->link;/*first node of second polynomial*/
105. /* till node of each polynomial not reaching their respective header node*/
106. while (a != poly1 && b != poly2)
107. {
108. /*both polynomials respective x,y, and z terms exponents are equal*/
109. if (a->xexp == b->xexp && a->yexp == b->yexp && a->zexp == b->zexp)
110. comp = 0;/*assign compare as 0*/
111. else if (a->xexp>b->xexp)
112. /*xterm's exponent of first polynomial is greater than second poly*/
113. comp=1;/*assign compare as 1*/
114. else if (a->xexp == b->xexp && a->yexp>b->yexp)
115. /*xterm exponent is eqaul but yterm exponent is greater*/
116. comp=1;/*assign compare as 1*/
117. else if(a->xexp==b->xexp && a->yexp==b->yexp && a->zexp>b->zexp)
118. /*xterm,yterm exponents are eqaul but zterm exponent is greater*/
119. comp=1 ;/*assign compare as 1*/
120. else comp= -1;/*assign compare as -1 for all other cases*/
121. switch (comp)
122. {
123. /*all x,y,z exponents terms are equal in both polynomial */
124. case 0: attach(polysum, a->coef + b->coef, a->xexp, a->yexp, a->zexp);
125. /*add x,y and zterms and create new node for sum*/
126. a = a->link;/*move to the next node in the first poly */
127. b=b->link;/*move to the next node in the second poly */
128. break;
129. /*first polynomial exponent terms are greater than second poly */
130. case 1: attach(polysum, a->coef, a->xexp, a->yexp, a->zexp);
131. /*create new node for sum for adding x, y and zterms of second poly to first poly */
132. a=a->link;/*move to the next node in the first poly */
133. break;
134. /*second polynomial exponent terms are greater than first poly */
135. case -1: attach(polysum,b->coef,b->xexp,b->yexp,b->zexp);
136. /*create new node for sum for adding x, y and zterms of first poly with second poly */
137. b=b->link;/*move to the next node in the second poly */
138. break;
139. }/*end switch*/
140. }/*end while*/
36. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 36 of 47 DS Lab Programs
141. while (a != poly1)/*take remaining terms from first polynomial and add it to polysum*/
142. {
143. attach(polysum, a->coef, a->xexp, a->yexp, a->zexp);
144. /*create new node and insert to the polysum-resultant poly*/
145. a=a->link;/*move to the next node in the first poly */
146. }/*end while*/
147. while (b != poly2)
148. /*take remaining terms from second polynomial and add it to polysum*/
149. {
150. attach(polysum, b->coef, b->xexp, b->yexp, b->zexp);
151. /*create new node and insert to the polysum - resultant poly*/
152. b=b->link;/*move to the next node in the second poly */
153. }/*end while*/
154.
155. }/*end addpoly*/
156.
157. void main( )
158. {
159. POLY *poly1, *poly2, *polysum;
160. clrscr();
161.
162. poly1 = (POLY*)malloc(sizeof(POLY));/*create first polynomial header node-poly1*/
163. poly1->link = poly1;/*link the header node to itself*/
164.
165. poly2 = (POLY*)malloc(sizeof(POLY));/*create second polynomial header node-poly2*/
166. poly2->link = poly2;/*link the header node to itself*/
167.
168. polysum = (POLY*)malloc(sizeof(POLY));/*create resultant polynomial header node-
polysum*/
169. polysum->link = polysum;/*link the header node to itself*/
170.
171. repandevalpoly();
172.
173. printf("nEnter the details for first polynomialn");
174. createpoly(poly1);
175. printf("nThe given first polynomial is:n");
176. display(poly1);
177.
178. printf("nEnter the details for Second polynomialn");
179. createpoly(poly2);
180. printf("nThe given second polynomial is:n");
181. display(poly2);
182.
183. addpoly(poly1,poly2,polysum);
184. printf("nThe resultant polynomial is:n");
185. display(polysum);
186.
187. getch();
188. }/* end main */
37. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 37 of 47 DS Lab Programs
OUTPUT:
38. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 38 of 47 DS Lab Programs
10. Design, Develop and Implement a menu driven Program in C for the following operations on
Binary Search Tree (BST) of Integers:
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
1. #include<stdio.h>
2. #include<conio.h>
3. #include<alloc.h>
4.
5.
6. struct BSTree
7. {
8. int data;
9. struct BStree *rlink, *llink;
10. };
11.
12.
13. typedef struct BSTree BST;
14.
15. /*function prototypes*/
16. BST* read_data( );
17. void insertBST(BST* root, BST* temp);
18. BST* CreateBST(BST *root);
19. void DisplayBST(BST* root);
20. int searchBST(BST *root, int key);
21.
22. /*read data for each node*/
23. BST *read_data()
24. {
25. BST *temp = (BST*)malloc(sizeof(BST));/*create a new node for every value*/
26. printf("Enter the number:n");
27. scanf("%d",&temp->data);
28. temp->rlink = temp->llink = 0;/*assign null value to rlink and llink of node*/
29. return temp;/*return the new node's address*/
30. }/*end read_data*/
31.
32. /*inset into Binary search tree*/
33. void insertBST(BST* root,BST* temp)
34. {
35. if (temp->data <= root->data)/*if current data is less than root data*/
36. {
37. if (root->llink == 0)/*if left link of root is null*/
38. root->llink = temp;/*assign new node[temp] to the left link of root*/
39. else
40. insertBST(root->llink, temp);
41. /*call the same function again by traversing towards left side*/
42. }
39. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 39 of 47 DS Lab Programs
43. else if(temp->data > root->data) /*if current data is greater than root data*/
44. {
45. if (root->rlink == 0)/*if right link of root is null*/
46. root->rlink = temp;/*assign new node[temp] to the right link of root*/
47. else
48. insertBST(root->rlink, temp);
49. /*call the same function again by traversing towards right side*/
50. }/*end else*/
51.
52. }/*end insertBST*/
53.
54. /*create Binary Seach Tree*/
55. BST * CreateBST(BST *root)
56. {
57. int n,i;
58. BST *temp=0;
59. printf("Enter the total no. of Numbersn");
60. scanf("%d",&n);
61. for (i = 0; i < n; i++)/*create node foreach number and insert into tree for each node*/
62. {
63. temp = read_data();/*read each number and store it in node*/
64. if (root == 0)/*if no root node*/
65. root = temp;/*assign new node as root*/
66. else
67. insertBST(root, temp);
68. /*call the same function and insert the number at left side if number is lesser else right side*/
69. }/*end for*/
70.
71. return(root);/*return root node*/
72. }/*end CreateBST*/
73.
74.
75. /*preorder traversal*/
76. void preorder(BST *root)
77. {
78. if (root != NULL)/*if root node is not null*/
79. {
80. printf("%dt", root->data);/*display the date*/
81. preorder(root->llink);/*call the same function by moving towards left link*/
82. preorder(root->rlink);/*call the same function by moving towards right link*/
83. }/*end for*/
84. }/*end preorder*/
85.
86.
87. /*inorder traversal*/
88. void inorder(BST *root)
89. {
90. if (root != NULL)/*if root node is not null*/
91. {
92. inorder(root->llink); /*call the same function by moving towards left link*/
40. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 40 of 47 DS Lab Programs
93. printf("%dt", root->data); /*display the date*/
94. inorder(root->rlink);/*call the same function by moving towards right link*/
95. }/*end if*/
96. }/*end indorder*/
97.
98.
99. /*inorder traversal*/
100. void postorder(BST *root)
101. {
102. if (root != NULL)/*display the date*/
103. {
104. postorder(root->llink); /*call the same function by moving towards left link*/
105. postorder(root->rlink);/*call the same function by moving towards left link*/
106. printf("%dt", root->data); /*display the date*/
107. }/*end if*/
108. }/*end postorder*/
109.
110.
111. /*Display Binary Search Tree*/
112. void DisplayBST(BST* root)
113. {
114. if(root==0)
115. printf("Binary Search Tree is Emptyn");
116. else
117. {
118. printf("nPreorder Traversal is:n");
119. preorder(root);
120. printf("nInorder Traversal is:n");
121. inorder(root);
122. printf("nPostorder Traversal is:n");
123. postorder(root);
124. }
125. }/*end indorder*/
126.
127. /*Search binary search tree */
128. int searchBST(BST *root, int key)
129. {
130. if (root == 0)
131. return (0);
132. if (key == root->data)
133. return(1);
134. if (key<root->data)
135. return searchBST(root->llink, key);
136. else
137. return searchBST(root->rlink, key);
138. }/*end indorder*/
41. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 41 of 47 DS Lab Programs
139.
140. void main( )
141. {
142. int ch,key,f;
143.
144. BST *root=0;
145. clrscr();
146.
147. while(1)
148. {
149. printf("nBinary Search Tree (BST) of Integersn");
150. printf("1.Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2n");
151. printf("2.Traverse the BST in Inorder, Preorder and Post Ordern");
152. printf("3.Search the BST for a given element (KEY)n");
153. printf("4.Delete n");
154. printf("5.Exitn");
155. printf("Enter the Choicen");
156. scanf("%d",&ch);
157.
158. switch(ch)
159. {
160. case 1: root=CreateBST(root);
161. break;
162. case 2: DisplayBST(root);
163. break;
164. case 3: printf("nEntr the number to be searched in the Binary Search Treen");
165. scanf("%d", &key);
166. f=searchBST(root, key);
167. if (f)
168. printf("nSearch successfuln");
169. else
170. printf("nSearch unsuccessful and key is not foundn");
171. break;
172. case 4: ;
173. break;
174. case 5: exit(0);
175. default: printf("Invalid Choicen");
176. } /* end switch*/
177.
178. } /* end while*/
179. } /*end main*/
42. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 42 of 47 DS Lab Programs
OUTPUT:
43. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 43 of 47 DS Lab Programs
11. Design, Develop and Implement a Program in C for the following operations on Graph(G) of
Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS method
1. #define SIZE 50 /* Size of Stack */
2. #include <stdio.h>
3. #include<conio.h>
4. char city[10][100];
5. int n, a[10][10], visit[10], start;
6.
7. /*Breadth First Search*/
8. void bfs(int start) /* start bfs*/
9. {
10. int i,j,f = -1, r = -1, q[10];
11. visit[start] = 1; /*start node visited, assign 1 for visited*/
12. q[++r] = start; /*insert start node no. into the queue*/
13.
14. while (f != r)/*till end of the queue is reached*/
15. {
16. i = q[++f]; /* dequeue and assign node to i */
17. if (i != start)/*node-i is not starting node*/
18. printf("%sn", city[i]);/*display city name*/
19. for (j = 0; j < n; j++) /* take each adjacent nodes*/
20. if (visit[j] == 0 && a[i][j] == 1)/*not visited and connected-has path*/
21. {
22. q[++r] = j; /* enqueue the node no*/
23. visit[j] = 1; /*assign visited as 1 for that node*/
24. } /*endif*/
25. } /*end while*/
26.
27. }/* end bfs*/
28.
29. /*Breadth First Search*/
30. void dfs(int i)/*i is start node*/
31. {
32. int j;
33. if(i!=start) /*node-i is not starting node*/
34. printf("%sn", city[i]); /*display city name*/
35. visit[i] = 1; /*node visited, assign 1 for visited*/
36.
37. for (j = 0; j<n; j++) /* take each adjacent nodes*/
38. if (visit[j]== 0 && a[i][j] == 1)/*not visited and connected-has path*/
39.
40. dfs(j);/*call dfs by passing adjacent node no.*/
41. } /*end dfs*/
44. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 44 of 47 DS Lab Programs
42. void main( )
43. {
44. int i, j;
45.
46. printf("nEnter the number of cities/nodesn");
47. scanf("%d", &n);
48.
49. printf("nEnter the City namesn");
50. for (i = 0; i<n; i++)
51. scanf("%s",city[i]);
52. printf("nEnter the adjacency matrixn");
53. for (i = 0; i<n; i++)
54. for (j = 0; j<n; j++)
55. scanf("%d", &a[i][j]);
56.
57. printf("Enter the starting vertexn");
58. scanf("%d", &start);
59. for (i = 0; i<n; i++)
60. visit[i] = 0; /* all nodes not yet visited*/
61. printf("Using BFS,The cities reachable from the %s city are:n", city[start]);
62. bfs(start);
63.
64. for (i = 0; i<n; i++)
65. visit[i] = 0; /* all nodes not yet visited*/
66. printf("Using DFS,The cities reachable from the %s city are:n", city[start]);
67. dfs(start);
68. getch();
69.
70. }/*end main*/
OUTPUT: Node 0: Bangalore, Node 1: mysore, Node 2: mandya, Node 3: hassan
45. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 45 of 47 DS Lab Programs
12. Given a File of N employee records with a set K of Keys(4-digit) which uniquely determine the
records in file F. Assume that file F is maintained in memory by a Hash Table(HT) of m memory
locations with L as the set of memory addresses (2-digit) of locations in HT. Let the keys in K
and addresses in L are Integers.
Design and develop a Program in C that uses Hash function H: K ®L as H(K)=K mod m
(remainder method), and implement hashing technique to map a given key K to the address
space L. Resolve the collision (if any) using linear probing.
1. #include <stdio.h>
2. #define msize 10 /*no of memory locations / Hash Table Size*/
3. int ht[msize];
4.
5. /*hash function returns the last digit of key*/
6. int hash(int key)
7. {
8. return key%msize; /*return remainder-last digit*/
9. }/*end hash*/
10.
11. void linear_probe(int hk,int key)
12. {
13. int i,flag=0;
14. for (i=hk+1;i<msize;i++)
15. /*check the hash table after the key index-2nd half of hash table*/
16. {
17. if (ht[i]==999)/*in hash table,free index is found-ie 999*/
18. {
19. ht[i]=key;/*assign the key value to hash table*/
20. flag=1;/*set flag as 1*/
21. break; /*teminate the for loop*/
22. }/*end if*/
23. }/*end for*/
24.
25. for(i=0;i<hk&&flag==0;i++)
26. /*check the hash table before the key index-1st half of hashtable*/
27. {
28. if (ht[i]==999)/*in hash table table,free index is found-ie 999*/
29. {
30. ht[i]=key;/*assign the key value to hash table*/
31. flag=1;/*set flag as 1*/
32. break;/*teminate the for loop*/
33. }/*end if*/
34. }/*end for*/
35. if (flag==0) /*if no index is free in hash table*/
36. printf("HASH Table is Full!!!n");
37. }/*end linear_probe*/
46. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 46 of 47 DS Lab Programs
38. void main( )
39. {
40. FILE *fp;
41. int n,i,key,hk;
42. char name[100];
43. clrscr();
44. for (i=0;i<msize;i++)/* all index positions of has table*/
45. ht[i]=999;/*assign 999 to array elements stating it is free slot in hash table*/
46.
47. fp=fopen("Employee.txt","w");/*opening employee file in writing mode*/
48. printf("Enter Total number of Employeesn");
49. scanf("%d",&n);
50. for(i=0;i<n;i++)
51. {
52. printf("Enter the 4 Digit Employee ID(key)n");
53. scanf("%d",&key);
54. printf("Enter the employee Namen");
55. scanf("%s",&name);
56. fprintf(fp,"%d %sn",key,name);/*writing employee details to file*/
57.
58. }/*end for*/
59. fclose(fp);/*close the employee file*/
60.
61. fp=fopen("Employee.txt","r");/*opening employee file in reading mode*/
62. while(1)/*as long as file content is available*/
63. {
64. fscanf(fp,"%d%s",&key,name);/*reading employee details from file*/
65. if(feof(fp)) break;/*end of file, terminate the loop*/
66. hk=hash(key);/*store the hashcode of the key*/
67. if (ht[hk]==999)/*array element for hashcode index of array is empty*/
68. ht[hk]=key;/*assign key value to the array element*/
69. else
70. { /* array element is not free*/
71. printf("Collision for key %d:n",key);
72. printf("Collision solved by Linear Probingnn");
73. linear_probe(hk,key);/*check hash table for linear probing*/
74. }/*end else*/
75. }/*end while*/
76. printf("-------------------------------n");
77. printf("HASH TABLEn");
78. printf("-------------------------------n");
79. printf("AddresstKeysn");
80. for (i=0;i<msize;i++)/* display Hash table*/
81. printf("%dt%dn",i,ht[i]);
82. fclose(fp);
83. getch( );
84. }/*end main*/
47. DATA STRUCTURES LABORATORY [ 15CSL38 ]
Prof. A. Syed Mustafa, HKBKCE. Page 47 of 47 DS Lab Programs
OUTPUT:
48.
HKBK COLLEGE of ENGINEERING
S.No. 22 / 1, Off. Manyata Tech Park, Nagawara, Bengaluru 560045. Karnataka
Tel : +91 80 25441722 / 3744 / 3690 / 3698 Fax: +91 80 25443813
Email: info@hkbkeducation.org URL: http://www.hkbkeducation.org
To empower the students through wholesome education & enable
the students to develope into highly qualified and trained
professionals with ethics and emerge as responsible citizens to
build a vibrant nation.
VISION
H K B K COLLEGE OF ENGINEERING
To achieve academic excellence in science, engineering and
technology through dedication to duty, innovation in teaching
and faith in human values.
To enable our students to develop into outstanding professional
with high ethical standards to face the challenges of 21st century.
To provide educational opportunities to the deprived and weaker
section of the society to uplift their socioeconomic status.
MISSION
To train skilled and ethical professionals with the ability to plan,
design, develop, organize and manage modern and traditional
information systems with the knowledge of information
technologies, services and organizations globally.
VISION
DEPT. OF INFORMATION SCIENCE & ENGINEERING
To impart high quality engineering education in the field of
Information Science and Technology with strong theoretical and
extensive practical training methodologies through innovation
and research to make worldclass Engineers.
MISSION