0% found this document useful (0 votes)
12 views

DS LAB Manual (2) Final

Uploaded by

459 Vineeth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

DS LAB Manual (2) Final

Uploaded by

459 Vineeth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 1
Develop a Program in C for the following:
a. Declare a calendar as an array of 7 elements (A dynamically Created array) to
represent 7 days of a week. Each Element of the array is a structure having three fields.
The first field is the name of the Day (A dynamically allocated String), the second field
is the date of the Day (An integer), and the third field is the description of the activity
for a particular day (A dynamically allocated String).
b. Write functions create (), read () and display (); to create the calendar, to read the data
from the keyboard and to print weeks activity details report on screen.
Program Code:
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
typedef struct {
char *name;
int date;
char *description;
} Day;
void create(Day *week, int size) {
for (int i = 0; i < size; i++) {
week[i].name = (char *)malloc(20 * sizeof(char));
week[i].description = (char *)malloc(100 * sizeof(char));
}
}

void read(Day *week, int size) {


for (int i = 0; i < size; i++) {
printf("Enter name of day %d: ", i + 1);
scanf("%s", week[i].name); printf("Enter
date: ");
scanf("%d", &week[i].date);
printf("Enter description: ");
scanf(" %[^\n]", week[i].description);
}
}
void display(Day *week, int size) {
printf("\nWeek's Activity Details:\n");for
(int i = 0; i < size; i++) {
printf("Day: %s, Date: %d, Activity: %s\n", week[i].name, week[i].date, week[i].description);
}
}
int main() {

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 1


PACE, Mangalore Data Structures Laboratory (BCSL305)
int size = 7; // 7 days in a week
Day *week = (Day *)malloc(size * sizeof(Day));
create(week, size);
read(week, size);
display(week, size);
for (int i = 0; i < size; i++) {
free(week[i].name);
free(week[i].description);
}
free(week);
return 0;
}
Execution:
INPUT:

Enter name of day 1: Monday


Enter date: 23
Enter description: Reading
Enter name of day 2: Tuesday
Enter date: 24
Enter description: Writing
Enter name of day 3: Wednesday
Enter date: 25
Enter description: Playing
Enter name of day 4: Thursday
Enter date: 26
Enter description: Coding
Enter name of day 5: Friday
Enter date: 27
Enter description: Browsing
Enter name of day 6: Saturday
Enter date: 28
Enter description: Assignment
Enter name of day 7: Sunday
Enter date: 29
Enter description: Shopping
OUTPUT:

Week's Activity Details:


Day: Monday, Date: 23, Activity: Reading
Day: Tuesday, Date: 24, Activity: Writing
Day: Wednesday, Date: 25, Activity: Playing
Day: Thursday, Date: 26, Activity: Coding
Day: Friday, Date: 27, Activity: Browsing
Day: Saturday, Date: 28, Activity: Assignment
Day: Sunday, Date: 29, Activity: Shopping

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 2


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 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.
c. Support the program with functions for each of the above operations. Don't use
Built-in functions.

PROGRAM CODE:
#include <stdio.h>

void readString(char* s, int maxLen, const char* prompt) {


printf("%s", prompt);
fgets(s, maxLen, stdin); int i = 0;
while (s[i] != '\n' && s[i] != '\0') i++; s[i] = '\0';
}

int findPattern(const char* str, const char* pat, int start) { int i, j;
for (i = start; str[i] != '\0'; i++) {
for (j = 0; pat[j] != '\0' && str[i + j] == pat[j]; j++); if (pat[j] == '\0')
return i;
}
return -1;
}

void replacePattern(char* str, const char* pat, const char* rep) {


char temp[1024];
int i = 0, j, k; int found = 0;
while (str[i] != '\0') {
int pos = findPattern(str, pat, i); if (pos != -1) {
found = 1;
for (j = 0; j < pos; j++) temp[j] = str[j];
for (k = 0; rep[k] != '\0'; k++, j++) temp[j] = rep[k]; i = pos;
while (str[i] == pat[i - pos]) i++;
while (str[i] != '\0') temp[j++] = str[i++];

temp[j] = '\0';
for (i = 0; temp[i] != '\0'; i++) str[i] = temp[i]; str[i] = '\0';
i = pos + k;
} else break;
}
if (!found) {
printf("Pattern not found in the string.\n");
}
}

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 3


PACE, Mangalore Data Structures Laboratory (BCSL305)
int main() {
char STR[1024], PAT[100], REP[100];
readString(STR, 1024, "Enter the main string (STR): ");
readString(PAT, 100, "Enter the pattern string (PAT): ");
readString(REP, 100, "Enter the replace string (REP): ");
replacePattern(STR, PAT, REP);
printf("Modified String: %s\n", STR); return 0;
}
Execution:

CASE 1:

Enter the main string (STR): Data Structures Laboratory


Enter the pattern string (PAT):
Enter the replace string (REP):_
Modified String: Data_Structures_Laboratory

CASE 2:

Enter the main string (STR): Find String


Enter the pattern string (PAT): Find
Enter the replace string (REP): Replace
Modified String: Replace String

CASE 3:

Enter the main string (STR): Executing C Program Enter the pattern string (PAT): C++
Enter the replace string (REP): Python
Pattern not found in the string.
Modified String: Executing C Program

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 4


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 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

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#define MAX 3
int arr[MAX],rev[MAX];
int top = -1;

int isFull() {
return (top == MAX -1)?1:0;
}
void push() {
int item;
if(isFull()){
printf("\nFull stack!\n");
return;
}
printf("Enter the Element to be Inserted\n");
scanf("%d",&item);
printf("\n%d pushed!\n",item); arr[++top]
= item;
}

int isEmpty() {
return (top == -1)?1:0;
}

void pop() { int


item;
if(isEmpty()) { printf("\nEmpty
stack!\n"); return;
}

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 5


PACE, Mangalore Data Structures Laboratory (BCSL305)
item = arr[top--];

printf("\n%d popped!\n",item);
}
void display(){
if(isEmpty()) {
printf("Empty stack!\n");
return;
}
else{
printf("\nStack Contents:\n");
for(int i=top;i>=0;i--){
printf("%d\t",arr[i]);

}
}
}
void pali()
{
int i=0,j=top, flag = 1;

if(top==-1){
printf("Push some elements into the stack first\n");
return;
}
else{
while(i<=top){
rev[j--]=arr[i++];

for(i=0;i<=top;i++){
if(arr[i]!=rev[i]){ flag
= 0;
}

}
}
if(flag){
for(i=0;i<=top;i++){
printf("%d\t",arr[i]);
}
printf("\nPalindrome\n");
}
else
printf("Not Palindrome\n");

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 6


PACE, Mangalore Data Structures Laboratory (BCSL305)
}
int main()
{
int item,choice, flag=1;
while(1)
{
printf("\n\n --------- STACK OPERATIONS\n”);
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Palindrome\n");
printf("4.Display\n");
printf("5.Exit\n");
printf(" ");
printf("\nEnter your choice:\t");
scanf("%d",&choice);

switch(choice)
{
case 1: push(); break;
case 2: pop();
break;
case 3: pali();
break;
case 4: display();
break;
case 5: printf("\nProgram Ternminated\n");
exit(0);

default: printf("\nInvalid choice:\n"); break;


}
}
return 0;
}
Execution:

-------- STACK OPERATIONS


1.Push
2.Pop
3.Palindrome
4.Display
5.Exit
Enter your choice: 3

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 7


PACE, Mangalore Data Structures Laboratory (BCSL305)
Push some elements into the stack first
-------- STACK OPERATIONS
1.Push
2.Pop
3.Palindrome
4.Display
5.Exit
Enter your choice: 4
Empty stack!
-------- STACK OPERATIONS
1.Push
2.Pop
3.Palindrome
4.Display
5.Exit
Enter your choice: 2
Empty stack!
-------- STACK OPERATIONS
1.Push
2.Pop
3.Palindrome
4.Display
5.Exit

Enter your choice: 1


Enter the Element to be Inserted 35
35 pushed!

-------- STACK OPERATIONS


1.Push
2.Pop
3.Palindrome
4.Display
5.Exit

Enter your choice: 1


Enter the Element to be Inserted 79
79 pushed!
-------- STACK OPERATIONS
1.Push

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 8


PACE, Mangalore Data Structures Laboratory (BCSL305)

2.Pop
3.Palindrome 4.Display
5.Exit
Enter your choice: 3 Not
Palindrome
-------- STACK OPERATIONS
1.Push
2.Pop
3.Palindrome
5.Exit

Enter your choice: 1


Enter the Element to be Inserted 35
35 pushed!
-------- STACK OPERATIONS
1.Push
2.Pop
3.Palindrome
4.Display
5.Exit
Enter your choice: 3
35 79 35
Palindrome

-------- STACK OPERATIONS


1. Push
2.Pop
3.Palindrome
4.Display
5.Exit

Enter your choice: 5


Program Ternminated

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 9


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 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.

PROGRAM CODE:

#define SIZE 50 /* Size of Stack */ #include


<ctype.h>
#include <stdio.h>
char s[SIZE];
int top = -1; /* Global declarations */

void push(char elem) /* Function for PUSH operation */


{
s[++top] = elem;
}

char pop() /* Function for POP operation */


{
return (s[top--]);
}

int pr(char elem) /* Function for precedence */


{
switch (elem){ case
'#': return 0; case '(':
return 1; case '+':
case '-': return 2;
case '*':
case '/':
case '%': return 3;
case '^': return 4;
}
}

void main() /* Main Program */


{
char infx[50], pofx[50], ch, elem;

int i = 0, k = 0;
printf("\n\nRead the Infix Expression ? "); scanf("%s",
infx);
push('#');
while ((ch = infx[i++]) != '\0'){ if
(ch == '(')
push(ch);

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 10


PACE, Mangalore Data Structures Laboratory (BCSL305)
else if (isalnum(ch)) pofx[k++]
= ch;
else if (ch == ')'){
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
}

else{ /* Operator */
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop(); push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */ pofx[k++]
= pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s \nPostfix Expn: %s\n", infx, pofx);
}

Execution:

INPUT:

Read the Infix Expression ? a/(b-c)*d+(e-f)

OUTPUT:

Given Infix Expn: a/(b-c)*d+(e-f)


Postfix Expn: abc-/d*ef-+

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 11


PACE, Mangalore Data Structures Laboratory (BCSL305)
EXPERIMENT: 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

PROGRAM CODE 5A:

#include <stdio.h>
#include <math.h>
#define MAX 20
struct stack
{
int top;
float str[MAX];
}s; //stack
char postfix[MAX]; //postfix

void push(float);
float pop ();
int isoperand(char);
float operate(float,float,char);

int main()
{
int i=0;
printf("Enter Expression:");
scanf("%s",postfix);
float ans,op1,op2;
while(postfix[i]!='\0'){
if(isoperand(postfix[i]))
push(postfix[i]-48);
else {
op1=pop();
op2=pop();
ans=operate(op1,op2,postfix[i]);
push(ans);
printf("%f %c %f = %f\n",op2,postfix[i],op1,ans);
}
i++;
}
printf("%f",s.str[s.top]);
}
int isoperand(char x)
{
if(x>='0' && x<='9')
return 1;
return 0;
}
Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 12
PACE, Mangalore Data Structures Laboratory (BCSL305)

void push(float x)
{
if(s.top==MAX-1)
printf("Stack is full\nStack overflow\n");
else
{
s.top++;
s.str[s.top]=x;

}
}

float pop()
{
if(s.top==-1)
{
printf("Stack is emplty\nSTACK UNDERFLOW\n");
}
else{
s.top--;
return s.str[s.top+1];
}
}

float operate(float op1,float op2,char a)


{
switch(a){
case '+' : return op2+op1; case
'-' : return op2-op1; case '*' :
return op2*op1; case '/' :
return op2/op1;
case '^' : return pow(op2,op1);
}

Execution:

INPUT:
Enter Expression:231*+9-

OUTPUT:
3.000000 * 1.000000 = 3.000000
2.000000 + 3.000000 = 5.000000
5.000000 - 9.000000 = -4.000000
-4.000000
Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 13
PACE, Mangalore Data Structures Laboratory (BCSL305)

// 5b. Towers of Hanoi

Solving Tower of Hanoi problem with n disks.

PROGRAM CODE: 5B
#include <stdio.h>
#include <math.h>
void tower(int n, char source, char temp,char destination)
{
if(n == 0)
return;
tower(n-1, source, destination, temp);
printf("\nMove disc %d from %c to %c", n, source, destination); tower(n-1, temp, source, destination); }
void main() {

int n;
printf("\nEnter the number of discs: \n");
scanf("%d", &n); tower(n, 'A', 'B', 'C');
printf("\n\nTotal Number of moves are: %d", (int)pow(2,n)-1);

}
Execution:

INPUT:
Enter the number of discs:
3

OUTPUT:
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C

Total Number of moves are: 7

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 14


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 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
PROGRAM CODE:
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
int CQ[SIZE];
int front=-1; int
rear=-1, ch;
int IsCQ_Full();
int IsCQ_Empty();
void CQ_Insert(int );
void CQ_Delet();
void CQ_Display();
void main()
{
while(1){
printf("1.Insert\n2.Delete\n3.Display\n4.Exit\n");
int ele;
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch){
case 1: if(IsCQ_Full())
printf("Circular Queue Overflow\n");
else{
printf("Enter the element to be inserted\n");
scanf("%d",&ele);
CQ_Insert(ele);
}
break;
case 2: if(IsCQ_Empty())
printf("Circular Queue Underflow\n");
else
CQ_Delet();
Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 15
PACE, Mangalore Data Structures Laboratory (BCSL305)
break;
case 3: if(IsCQ_Empty())
printf("Circular Queue Underflow\n");
else
CQ_Display();
break;
case 4: exit(0);
Page 18
}
}
}
void CQ_Insert(int item)
{
if(front==-1)
front++;
rear = (rear+1)%SIZE;
CQ[rear] =item;
}
void CQ_Delet()
{
int item;
item=CQ[front];
printf("Deleted element is: %d\n",item);
front = (front+1)%SIZE;
}
void CQ_Display()
{
int i;
if(front==-1)
printf("Circular Queue is Empty\n");
else{
printf("Elements of the circular queue are..\n");
i=front;
while(i!=rear){
printf("%d\t",CQ[i]);
i=(i+1)%SIZE;
}
printf("%d\n",CQ[i]);
}
}
int IsCQ_Full()
{
if(front ==(rear+1)%SIZE)

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 16


PACE, Mangalore Data Structures Laboratory (BCSL305)
return 1;
return 0;
}
int IsCQ_Empty()
{
if(front == -1)
return 1;

return 0;
}
Page 19
Execution:
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice 3
Circular Queue Underflow
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice 2
Circular Queue Underflow
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice 1
Enter the element to be inserted
21
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice 1
Enter the element to be inserted
45
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice1

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 17


PACE, Mangalore Data Structures Laboratory (BCSL305)
Enter the element to be inserted
97
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice 1
Circular Queu Overflow
1.Insert
2.Delete
3.Display

4.Exit
Enter your choice 3
Elements of the circular queue are..
21 45 97
Page 20
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice
2
Deleted element is: 21
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice
4
Program Terminated

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 18


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT 7
Develop a menu driven Program in C for the following operations on Singly Linked List
(SLL) of Student Data with the fields: USN, Name, Programme, 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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int count=0;
struct stud
{
long int ph;
int sem;
char name[15],usn[15],brnch[8];
struct stud *next;
};

struct stud *head=NULL,*tail=NULL,*temp=NULL,*newnode=NULL;

void create(long int p,int s,char na[20],char u[20],char b[20])


{
newnode =(struct stud*)malloc(sizeof(struct stud));
newnode->ph=p;
newnode->sem=s;
strcpy(newnode->name,na);
strcpy(newnode->usn,u);
strcpy(newnode->brnch,b);
newnode->next=NULL;
count++;
if(head==NULL){
head=newnode;
return;
}
else{
newnode->next=head;
head=newnode;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 19


PACE, Mangalore Data Structures Laboratory (BCSL305)
}
}
void display()
{
temp=head;
if(temp==NULL){

printf("\nlist is empty\n");
}
else{
printf("student details are as follows:\n");
while(temp!=NULL){
printf("\n************** \n");
printf("NAME:%s\nUSN:%s\nBRANCH:%s\nSEM:%d\nPHONE NO.:%ld\n",temp-
>name,temp->usn,temp->brnch,temp->sem,temp->ph);
printf("\n*************** \n");
temp=temp->next;
}
printf("\nNo. of nodes=%d\n",count);
}
}
void insert_head(long int p,int s,char na[20],char u[20],char b[20])
{
newnode =(struct stud*)malloc(sizeof(struct stud));
newnode->ph=p;
newnode->sem=s;
strcpy(newnode->name,na);
strcpy(newnode->usn,u);
strcpy(newnode->brnch,b);
newnode->next=NULL;
count++;

if(head == NULL){
head = newnode;
return;
}
newnode->next = head;
head = newnode;

}
void insert_tail(long int p,int s,char na[20],char u[20],char b[20])
{
newnode =(struct stud*)malloc(sizeof(struct stud));

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 20


PACE, Mangalore Data Structures Laboratory (BCSL305)
newnode->ph=p;
newnode->sem=s;
strcpy(newnode->name,na);
strcpy(newnode->usn,u);
strcpy(newnode->brnch,b);
newnode->next=NULL;
count++;
if(head == NULL){
head = newnode;
return;

}
temp = head;
while(temp->next !=NULL)
temp = temp->next;
temp->next = newnode;
tail=temp;

}
void delete_head()
{
temp=head;
if(temp==NULL){
printf("list is empty\n");
return;
}
else{
head=head->next;
printf("deleted node is:\n");
printf(" \n");
printf("NAME:%s\nUSN:%s\nBRANCH:%s\nSEM:%d\nPHONE NO.:%ld\n",temp-
>name, temp->usn,temp->brnch,temp->sem,temp->ph);
printf(" \n");
free(temp);
count--;
}
}
void delete_tail()
{
if(head == NULL){
printf("List Empty\n");
return;
}

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 21


PACE, Mangalore Data Structures Laboratory (BCSL305)
else if(head->next == NULL) {
free(head);
}
else {
temp = head;
while(temp->next != NULL){
tail = temp;
temp = temp->next;
}
printf("deleted node is:\n");
printf("\n");
printf("NAME:%s\nUSN:%s\nBRANCH:%s\nSEM:%d\nPHONE NO.:%ld\n",temp-
>name,temp->usn,temp->brnch,temp->sem,temp->ph);
printf("\n");
free(temp);

tail->next = NULL;
}
count--;
}
void main()
{
int choice,num,i;
long int ph;
int sem;
char name[20],usn[20],brnch[20];

while(1){
printf("--------MENU-----------\n");
printf("1.create\n2.Insert from head\n3.Insert from tail\n4.Delete from head\n5.Delete from
tail\n6.display\n7.exit\n");
printf(" \n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\nEnter the Number of students\n");
scanf("%d",&num);
for(i=0;i<num;i++){
printf("Enter the %d Students name usn branch sem phno.respectively\n",i+1);
scanf("%s%s%s%d%ld",name,usn,brnch,&sem,&ph);
create(ph,sem,name,usn,brnch);
}

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 22


PACE, Mangalore Data Structures Laboratory (BCSL305)
break;
case 2:
printf("enter the name usn branch sem phno. of the student respectively\n");
scanf("%s%s%s%d%ld",name,usn,brnch,&sem,&ph);
insert_head(ph,sem,name,usn,brnch);
break;
case 3:
printf("enter the name usn branch sem phno. of the student respectively\n");
scanf("%s%s%s%d%ld",name,usn,brnch,&sem,&ph);
insert_tail(ph,sem,name,usn,brnch);
break;
case 4:
delete_head();
break;
case 5:
delete_tail();
break;
case 6:

display();
break;
case 7: printf("Program Terminated\n");
exit(0);
default:printf("invalid option\n");
}
}
}
Execution:
dept-cse@deptcse-desktop:~$ ./a.out
--------MENU-----------
1.create
2.Insert from head
3.Insert from tail
4.Delete from head
5.Delete from tail
6.display
7.exit

Enter your choice


6
list is empty
Enter your choice
4

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 23


PACE, Mangalore Data Structures Laboratory (BCSL305)
list is empty
Enter your choice
5
List Empty
Enter your choice
1
Enter the Number of students
1
Enter the 1 Students name usn branch sem phno.respectively
adil
32
cs
3
897987896
Enter your choice
6
student details are as follows:
**************
NAME:adil
USN:32
BRANCH:cs
SEM:3
PHONE NO.:897987896

***************
No. of nodes=1
Enter your choice
2
enter the name usn branch sem phno. of the student respectively
bob
78
is
5
98079866
Enter your choice
6
student details are as follows:
**************
NAME:bob
USN:78
BRANCH:is
SEM:5
PHONE NO.:98079866

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 24


PACE, Mangalore Data Structures Laboratory (BCSL305)
***************
**************
NAME:adil
USN:32
BRANCH:cs
SEM:3
PHONE NO.:897987896
***************
No. of nodes=2
Enter your choice
3
enter the name usn branch sem phno. of the student respectively
wilson
99
me
7
9866755555
Enter your choice
6
student details are as follows:
**************
NAME:bob
USN:78
BRANCH:is
SEM:5
PHONE NO.:98079866

***************
**************
NAME:adil
USN:32
BRANCH:cs
SEM:3
PHONE NO.:897987896
***************
**************
NAME:wilson
USN:99
BRANCH:me
SEM:7
PHONE NO.:9866755555
***************
No. of nodes=3

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 25


PACE, Mangalore Data Structures Laboratory (BCSL305)
Enter your choice
4
deleted node is:

NAME:bob
USN:78
BRANCH:is
SEM:5
PHONE NO.:98079866

Enter your choice


6
student details are as follows:
**************
NAME:adil
USN:32
BRANCH:cs
SEM:3
PHONE NO.:897987896
***************
**************
NAME:wilson
USN:99
BRANCH:me
SEM:7
PHONE NO.:9866755555
***************
No. of nodes=2
Enter your choice
5

deleted node is:


NAME:wilson
USN:99
BRANCH:me
SEM:7
PHONE NO.:9866755555
Enter your choice
6
student details are as follows:
**************
NAME:adil
USN:32

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 26


PACE, Mangalore Data Structures Laboratory (BCSL305)
BRANCH:cs
SEM:3
PHONE NO.:897987896
***************
No. of nodes=1
Enter your choice
7
Program Terminated

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 27


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 8
Develop 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

Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Employee Structure
typedef struct Employee {
char ssn[20];
char name[100];
char dept[50];
char designation[50];
double sal;
char phNo[15];
struct Employee *prev, *next;
} Employee;
// Function Declarations
Employee* createEmployee();
Employee* insertAtEnd(Employee* head);
void display(Employee* head);
int countNodes(Employee* head);
Employee* deleteAtEnd(Employee* head);
Employee* insertAtFront(Employee* head);
Employee* deleteAtFront(Employee* head);
// Main Function
int main() {
Employee *head = NULL;
int choice, count;
while(1) {
printf("\nMenu:\n");
printf("1. Insert Employee at End\n");

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 28


PACE, Mangalore Data Structures Laboratory (BCSL305)
printf("2. Display Employees\n");
printf("3. Count Employees\n");
printf("4. Delete Employee at End\n");
printf("5. Insert Employee at Front\n");
printf("6. Delete Employee at Front\n");
printf("7. Exit\n");
printf("Enter your choice: ");

scanf("%d", &choice);
switch(choice) {
case 1: head = insertAtEnd(head); break;
case 2: display(head); break;
case 3: count = countNodes(head);
printf("Total number of employees: %d\n", count);
break;
case 4: head = deleteAtEnd(head); break;
case 5: head = insertAtFront(head); break;
case 6: head = deleteAtFront(head); break;
case 7: exit(0);
default: printf("Invalid choice!\n");
}
}
return 0;
}
// Function Definitions
Employee* createEmployee() {
Employee *newNode = (Employee*)malloc(sizeof(Employee));
printf("Enter SSN: ");
scanf("%s", newNode->ssn);
printf("Enter Name: ");
scanf("%s", newNode->name); // Use fgets for multi-word names
printf("Enter Department: ");
scanf("%s", newNode->dept);
printf("Enter Designation: ");
scanf("%s", newNode->designation);
printf("Enter Salary: ");
scanf("%lf", &newNode->sal);
printf("Enter Phone Number: ");
scanf("%s", newNode->phNo);
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
Employee* insertAtEnd(Employee* head) {
Employee *newNode = createEmployee();
if (head == NULL) {

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 29


PACE, Mangalore Data Structures Laboratory (BCSL305)
return newNode;
} else {
Employee *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
return head;
}
}

void display(Employee* head) {

Employee *temp = head;

if (head == NULL) {
printf("List is empty!\n");
return;
}
while (temp != NULL) {
printf("SSN: %s, Name: %s, Dept: %s, Designation: %s, Salary: %.2f, Phone No: %s\n",
temp->ssn, temp->name, temp->dept, temp->designation, temp->sal, temp->phNo);

temp = temp->next;
}
}
int countNodes(Employee* head) {
int count = 0;
Employee *temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
Employee* deleteAtEnd(Employee* head) {
if (head == NULL) {
printf("List is already empty!\n");
return NULL;
} else if (head->next == NULL) {
free(head);
return NULL;
} else {
Employee *temp = head;
while (temp->next != NULL) {

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 30


PACE, Mangalore Data Structures Laboratory (BCSL305)
temp = temp->next;
}
temp->prev->next = NULL;
free(temp);
return head;
}
}
Employee* insertAtFront(Employee* head) {
Employee *newNode = createEmployee();
if (head == NULL) {
return newNode;
} else {
newNode->next = head;
head->prev = newNode;
return newNode;
}
}

Employee* deleteAtFront(Employee* head) {


if (head == NULL) {

printf("List is already empty!\n");


return NULL;
} else {
Employee *temp = head;
head = head->next;
if (head != NULL) head->prev = NULL;
free(temp);
return head;
}
}

Execution
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 1
Enter SSN: 123

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 31


PACE, Mangalore Data Structures Laboratory (BCSL305)
Enter Name: Rahul
Enter Department: Finance
Enter Designation: Manager
Enter Salary: 45000
Enter Phone Number: 87636
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 1
Enter SSN: 124
Enter Name: Arun
Enter Department: HR
Enter Designation: Engineer
Enter Salary: 30000
Enter Phone Number: 12345
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front

7. Exit
Enter your choice: 2
SSN: 123, Name: Rahul, Dept: Finance, Designation: Manager, Salary: 45000.00, Phone No: 87636
SSN: 124, Name: Arun, Dept: HR, Designation: Engineer, Salary: 30000.00, Phone No: 12345
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 3
Total number of employees: 2
Menu:
1. Insert Employee at End
2. Display Employees

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 32


PACE, Mangalore Data Structures Laboratory (BCSL305)
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 4
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 2
SSN: 123, Name: Rahul, Dept: Finance, Designation: Manager, Salary: 45000.00, Phone No: 87636
Menu:
1. Insert Employee at End

2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 5
Enter SSN: 134
Enter Name: krish
Enter Department: finace
Enter Designation: Accountant
Enter Salary: 20000
Enter Phone Number: 1234

Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 2
SSN: 134, Name: krish, Dept: finace, Designation: Accountant, Salary: 20000.00, Phone No: 1234
SSN: 123, Name: Rahul, Dept: Finance, Designation: Manager, Salary: 45000.00, Phone No: 87636
Menu:
1. Insert Employee at End

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 33


PACE, Mangalore Data Structures Laboratory (BCSL305)
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 6
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice: 2
SSN: 123, Name: Rahul, Dept: Finance, Designation: Manager, Salary: 45000.00, Phone No: 87636
Menu:
1. Insert Employee at End
2. Display Employees
3. Count Employees
4. Delete Employee at End
5. Insert Employee at Front
6. Delete Employee at Front
7. Exit
Enter your choice:

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 34


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 9
Develop a Program in C for the following operations on Singly Circular Linked List (SCLL) with
header nodes

g. Represent and Evaluate a Polynomial P(x,y,z) = 6x^2 y^2 z - 4yz^5 +3x^3 yz+2xy^5 z - 2xyz^3

h. 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

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct Term {


int coeff, xExp, yExp, zExp;
struct Term *next;
} Term;

// Function to create a new term


Term* createTerm(int coeff, int xExp, int yExp, int zExp) {
Term *newTerm = (Term*)malloc(sizeof(Term));
newTerm->coeff = coeff;
newTerm->xExp = xExp;
newTerm->yExp = yExp;
newTerm->zExp = zExp;
newTerm->next = NULL;
return newTerm;
}

// Function to insert a term in the polynomial


void insertTerm(Term **head, int coeff, int xExp, int yExp, int zExp) {
Term *newTerm = createTerm(coeff, xExp, yExp, zExp);
if (*head == NULL) {
*head = newTerm;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 35


PACE, Mangalore Data Structures Laboratory (BCSL305)

newTerm->next = *head;
} else {

Term *temp = *head;


while (temp->next != *head) {
temp = temp->next;
}
temp->next = newTerm;
newTerm->next = *head;
}
}

// Function to evaluate a polynomial


double evaluatePolynomial(Term *head, double x, double y, double z) {
double result = 0.0;
if (head == NULL) return result;
Term *temp = head;
do {
result += temp->coeff * pow(x, temp->xExp) * pow(y, temp->yExp) * pow(z, temp->zExp);
temp = temp->next;
} while (temp != head);
return result;
}

// Function to add two polynomials


// Note: This is a simplified version and assumes terms are in the same order
Term* addPolynomials(Term *head1, Term *head2) {
Term *sumHead = NULL;
Term *temp1 = head1, *temp2 = head2;
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;
do {
insertTerm(&sumHead, temp1->coeff + temp2->coeff, temp1->xExp, temp1->yExp, temp1->zExp);
temp1 = temp1->next;
temp2 = temp2->next;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 36


PACE, Mangalore Data Structures Laboratory (BCSL305)

} while (temp1 != head1 && temp2 != head2);


return sumHead;
}

int main() {
Term *poly1 = NULL, *poly2 = NULL, *polySum = NULL;
int coeff, xExp, yExp, zExp;
int n, i;
double x, y, z, result;

// Input for POLY1

printf("Enter the number of terms for POLY1: ");


scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter coeff, x exponent, y exponent, z exponent for term %d: ", i + 1);
scanf("%d %d %d %d", &coeff, &xExp, &yExp, &zExp);
insertTerm(&poly1, coeff, xExp, yExp, zExp);
}

// Input for POLY2


printf("Enter the number of terms for POLY2: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter coeff, x exponent, y exponent, z exponent for term %d: ", i + 1);
scanf("%d %d %d %d", &coeff, &xExp, &yExp, &zExp);
insertTerm(&poly2, coeff, xExp, yExp, zExp);
}

// Add POLY1 and POLY2


polySum = addPolynomials(poly1, poly2);

// Evaluate POLY1
printf("Enter values for x, y, and z to evaluate POLY1: ");
scanf("%lf %lf %lf", &x, &y, &z);

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 37


PACE, Mangalore Data Structures Laboratory (BCSL305)

result = evaluatePolynomial(poly1, x, y, z);


printf("POLY1(%lf, %lf, %lf) = %lf\n", x, y, z, result);

// Display POLYSUM
printf("POLYSUM(x, y, z) = ");
Term *temp = polySum;
if (temp != NULL) {
do {
printf("%+dx^%dy^%dz ", temp->coeff, temp->xExp, temp->yExp, temp->zExp);
temp = temp->next;

} while (temp != polySum);


printf("\n");
} else {
printf("0\n"); // POLYSUM is empty
}
// Free memory (not shown, but important in a complete program)

return 0;
}

Execution

Enter the number of terms for POLY1: 3


Enter coeff, x exponent, y exponent, z exponent for term 1: 6 2 2 1
Enter coeff, x exponent, y exponent, z exponent for term 2: -4 0 1 5
Enter coeff, x exponent, y exponent, z exponent for term 3: 3 3 1 1
Enter the number of terms for POLY2: 2
Enter coeff, x exponent, y exponent, z exponent for term 1: 2 1 5 1
Enter coeff, x exponent, y exponent, z exponent for term 2: -2 1 1 3
Enter values for x, y, and z to evaluate POLY1: 1 1 1
POLY1(1.000000, 1.000000, 1.000000) = 5.000000
POLYSUM(x, y, z) = +6x^2y^2z -4yz^5 +3x^3yz +2xy^5z -2xyz^3

Program Terminated

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 38


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 10
Develop a menu driven Program in C for the following operations on Binary Search Tree (BST)
of Integers.
i. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2

j. Traverse the BST in Inorder, Preorder and Post Order

k. Search the BST for a given element (KEY) and report the appropriate message

l. Exit

Program code :

#include <stdio.h>
#include <stdlib.h>
// Define a structure for BST nodes
struct BSTNode {
int data;
struct BSTNode *left, *right;
};
// Function to create a new BST node
struct BSTNode* newNode(int item) {
struct BSTNode* temp = (struct BSTNode*)malloc(sizeof(struct BSTNode));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Function to insert a new node with a given key in the BST
struct BSTNode* insert(struct BSTNode* node, int key) {
// If the tree is empty, return a new node
if (node == NULL) return newNode(key);
// Otherwise, recur down the tree
if (key < node->data)
node->left = insert(node->left, key);
else if (key > node->data)
node->right = insert(node->right, key);
// return the (unchanged) node pointer
return node;
}
// Inorder traversal of BST

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 39


PACE, Mangalore Data Structures Laboratory (BCSL305)

void inorder(struct BSTNode* root) {


if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
// Preorder traversal of BST
void preorder(struct BSTNode* root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// Postorder traversal of BST
void postorder(struct BSTNode* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
// Function to search a given key in a given BST
struct BSTNode* search(struct BSTNode* root, int key) {
// Base Cases: root is null or key is present at root
if (root == NULL || root->data == key)
return root;
// Key is greater than root's key
if (root->data < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
// Driver Program to test above functions
int main() {
struct BSTNode* root = NULL;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 40


PACE, Mangalore Data Structures Laboratory (BCSL305)

int choice, key;


int data[] = {6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2};
int n = sizeof(data) / sizeof(data[0]);

// Creating BST
for(int i = 0; i < n; i++) {
root = insert(root, data[i]);
}
do {
printf("\nMenu\n");
printf("1. Display Inorder\n");
printf("2. Display Preorder\n");
printf("3. Display Postorder\n");
printf("4. Search\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Inorder traversal: ");
inorder(root);
break;
case 2:
printf("Preorder traversal: ");
preorder(root);
break;
case 3:
printf("Postorder traversal: ");
postorder(root);
break;
case 4:
printf("Enter the element to search: ");
scanf("%d", &key);
if (search(root, key) != NULL)
printf("Element found\n");
else
printf("Element not found\n");

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 41


PACE, Mangalore Data Structures Laboratory (BCSL305)

break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice\n");
}
} while (choice != 5);
return 0;
}

Output :

Menu
1. Display Inorder
2. Display Preorder
3. Display Postorder
4. Search
5. Exit
Enter your choice: 1
Inorder traversal: 2 5 6 7 8 9 14 15 24
Menu
1. Display Inorder
2. Display Preorder
3. Display Postorder
4. Search
5. Exit
Enter your choice: 2
Preorder traversal: 6 5 2 9 8 7 15 14 24
Menu
1. Display Inorder
2. Display Preorder
3. Display Postorder
4. Search
5. Exit
Enter your choice: 3
Postorder traversal: 2 5 7 8 14 24 15 9 6

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 42


PACE, Mangalore Data Structures Laboratory (BCSL305)

Menu
1. Display Inorder
2. Display Preorder
3. Display Postorder
4. Search
5. Exit
Enter your choice: 4
Enter the element to search: 8
Element found

Menu
1. Display Inorder
2. Display Preorder
3. Display Postorder
4. Search
5. Exit
Enter your choice: 5
Exiting...

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 43


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 11
Develop a Program in C for the following operations on Graph(G) of Cities

m. Create a Graph of N cities using Adjacency Matrix.

n. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS
method

#include <stdio.h>
#include <stdlib.h>

#define MAX 100 // Maximum number of cities

// Global Variables
int adjMatrix[MAX][MAX]; // Adjacency matrix to store the graph
int visited[MAX]; // Array to keep track of visited cities
int n; // Number of cities

// Function to create the graph


void createGraph() {
int i, j, edges, origin, destin;

printf("Enter number of cities: ");


scanf("%d", &n);

// Initialize adjacency matrix to 0


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
adjMatrix[i][j] = 0;
}
}

printf("Enter number of roads between the cities: ");


scanf("%d", &edges);

for (i = 0; i < edges; i++) {


printf("Enter origin and destination cities numbers between 0 and %d: ", n-1);
scanf("%d %d", &origin, &destin);
adjMatrix[origin][destin] = 1;
}
}

// DFS function
void DFS(int city) {
int i;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 44


PACE, Mangalore Data Structures Laboratory (BCSL305)

printf("%d ", city);


visited[city] = 1;

for (i = 0; i < n; i++) {


if (adjMatrix[city][i] == 1 && !visited[i]) {
DFS(i);
}
}
}

// BFS function
void BFS(int startCity) {
int queue[MAX], front = 0, rear = -1, i;
visited[startCity] = 1;
queue[++rear] = startCity;

while (front <= rear) {


int currentCity = queue[front++];
printf("%d ", currentCity);

for (i = 0; i < n; i++) {


if (adjMatrix[currentCity][i] == 1 && !visited[i]) {
queue[++rear] = i;
visited[i] = 1;
}
}
}
}

// Main function
int main() {
int choice, startCity;

createGraph();

printf("Enter the starting city number between 0 and %d: ", n-1);
scanf("%d", &startCity);

printf("\nChoose method to find reachable cities:\n");


printf("1. Depth First Search (DFS)\n");
printf("2. Breadth First Search (BFS)\n");
scanf("%d", &choice);

// Reset visited array


for (int i = 0; i < n; i++) visited[i] = 0;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 45


PACE, Mangalore Data Structures Laboratory (BCSL305)

if (choice == 1) {
printf("Cities reachable from city %d using DFS:\n", startCity);
DFS(startCity);
} else if (choice == 2) {
printf("Cities reachable from city %d using BFS:\n", startCity);
BFS(startCity);
} else {
printf("Invalid choice!\n");
}

return 0;
}

Enter number of cities: 5


Enter number of roads between the cities: 6
Enter origin and destination cities numbers between 0 and 4: 0 1
Enter origin and destination cities numbers between 0 and 4: 0 2
Enter origin and destination cities numbers between 0 and 4: 1 3
Enter origin and destination cities numbers between 0 and 4: 1 4
Enter origin and destination cities numbers between 0 and 4: 2 3
Enter origin and destination cities numbers between 0 and 4: 3 4
Enter the starting city number between 0 and 4: 0
Choose method to find reachable cities:
1. Depth First Search (DFS)
2. Breadth First Search (BFS)
1
Cities reachable from city 0 using DFS:
01342
2
Cities reachable from city 0 using BFS:
01234

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 46


PACE, Mangalore Data Structures Laboratory (BCSL305)

EXPERIMENT: 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. 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.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int create(int);
void display (int[]);

void linear_prob(int a[], int key, int num);

int main()

int a[MAX],num,key,i; int


ans=1;
printf(" collision handling by linear probing : \n"); for
(i=0;i<MAX;i++){
a[i] = -1;

do{

printf("\n Enter the data");


scanf("%4d", &num);
key=create(num);
linear_prob(a,key,num);
printf("\n Do you wish to continue ? (1/0) "); scanf("%d",&ans);
}while(ans);

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 47


PACE, Mangalore Data Structures Laboratory (BCSL305)

display(a);

printf("\nProgram Terminated\n");
return 0;
}

int create(int num)

int key;
key=num%100;
return key;
}

void linear_prob(int a[MAX], int key, int num)

int flag, i, count=0;


flag=0; if(a[key]==
-1){ a[key] = num;
}

else{

printf("\nCollision Detected...!!!\n");
for(i=key; i!=(key-1); i=(i+1)%MAX) {
count++;
if(a[i] == -1){ a[i]
= num;

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 48


PACE, Mangalore Data Structures Laboratory (BCSL305)

flag =1;

printf("Collision avoided successfully using LINEAR PROBING\n"); break;


}

if(count == MAX){ printf("\n


Hash table is full"); display(a);
exit(1);

void display(int a[MAX])

int i,choice;

printf("1.Display ALL\n 2.Filtered Display\n");


scanf("%d",&choice);
if(choice==1){

printf("\n the hash table is\n");


for(i=0; i<MAX; i++) printf("\n
%d %d ", i, a[i]);
}

else{

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 49


PACE, Mangalore Data Structures Laboratory (BCSL305)

printf("\n the hash table is\n");


for(i=0; i<MAX; i++) if(a[i]!=-
1){
printf("\n %d %d ", i, a[i]);
continue;
}

Execution

dept-cse@deptcse-desktop:~$ gcc Lab12.c


dept-cse@deptcse-desktop:~$ ./a.out collision
handling by linear probing :

Enter the data7898

Do you wish to continue ? (1/0) 1

Enter the data5698

Collision Detected...!!!

Collision avoided successfully using LINEAR PROBING

Do you wish to continue ? (1/0) 1

Enter the data8899

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 50


PACE, Mangalore Data Structures Laboratory (BCSL305)

Collision Detected...!!!

Collision avoided successfully using LINEAR PROBING

Do you wish to continue ? (1/0) 1

Enter the data3200

Collision Detected...!!!

Collision avoided successfully using LINEAR PROBING

Do you wish to continue ? (1/0) 1

Enter the data4301

Collision Detected...!!!

Collision avoided successfully using LINEAR PROBING

Do you wish to continue ? (1/0) 1

Enter the data6666

Do you wish to continue ? (1/0) 1

Enter the data5667

Do you wish to continue ? (1/0) 1

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 51


PACE, Mangalore Data Structures Laboratory (BCSL305)

Enter the data3266

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 52


PACE, Mangalore Data Structures Laboratory (BCSL305)

Collision Detected...!!!

Collision avoided successfully using LINEAR PROBING

Do you wish to continue ? (1/0) 0

1. Display ALL

2. Filtered Display
2

the hash table is

0 8899

1 3200

2 4301

66 6666

67 5667

68 3266

98 7898

99 5698

Program Terminated

Prof.Seetha Das V, Assistant Professor CSE (ICSB) Page 53

You might also like