0% found this document useful (0 votes)
35 views59 pages

BCSL305 DS LAB Manual Updated

Uploaded by

keerthan050604
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views59 pages

BCSL305 DS LAB Manual Updated

Uploaded by

keerthan050604
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

LAB MANUAL

Data Structures Laboratory


(BCSL305)

III SEMESTER
(Computer Science and Engineering/
Information Science and Engineering)

Prepared by Approved by

Mr. Subrahmanya HM HOD PRINCIPAL


Asst. Prof. Department of CSE, Department of CSE, GCEM, Bangalore
GCEM, Bangalore GCEM, Bangalore

Department of Computer Science & Engineering


Gopalan College of Engineering and Management
(An ISO 9001:2008 Certified Institution)
Approved by AICTE | Recognised by Govt. Of Karnataka

Affiliated to Visvesvaraya Technological University Belgaum (VTU)

N0. 181/1, 182/1, Hoody Village, Sonnenahalli, K R Puram, Whitefield, B ANGALORE- 560 048

Tel: 080- 42229748 | Email : [email protected] | www.gopalancolleges.com


Gopalan College of Engineering and Management
(Accredited by NAAC, 2(f) status by UGC & ISO 9001:2015 certified)
Approved by All India Council for Technical Education (AICTE), New Delhi

Affiliated to Visvesvaraya Technological University (VTU), Belagavi, Karnataka


GCEM
Recognised by Govt. of Karnataka

181/1, 182/1, Sonnenahalli, Hoodi, K.R.Puram, Whitefield, Bangalore, Karnataka - 560 048
Phone No: 080 – 42229748 Email: [email protected] Website: www.gopalancolleges.com/gcem

Department of Computer Science and Engineering


VISION

To achieve excellent standards in learning by imparting quality education with extensive


research work in computer science and engineering to meet industrial and societal needs.
MISSION

M1: To impart state-of-the-art education in computer science & engineering and enhance the
skills of students in diverse domains.

M2: To establish research facilities and industry institute interaction for promoting
collaborative activities.

M3: To instill moral and ethical values and interpersonal skills to the students.
Program Educational Objectives (PEOs)

PEO1: The graduates of CSE will have the ability to demonstrate the engineering skills
across varied technological platforms.

PEO2: The graduates of CSE will have the skills to promote technical research and work in
the direction towards industrial requirements.

PEO3: Graduates will prove themselves to be ethically sound and socially responsible
engineers.

Program Specific Outcomes (PSOs)


PSO1: Ability to apply the engineering knowledge acquired in a vast range of multi-
disciplinary domains.

PSO2: Ability to represent themselves in the field of research and elevate themselves
towards industrial standards.

PSO3: Ability to exhibit the technical capabilities for the betterment of humanity.
PROGRAM OUTCOMES

Apply the knowledge of mathematics, science, engineering


PO-1 Engineering Knowledge fundamentals, and an engineering specialization to the solution of
complex engineering problems.
Identify, formulate, review research literature, and analyze
PO-2 complex engineering problems reaching substantiated conclusions
Problem Analysis
using first principles of mathematics, natural sciences, and
engineering sciences.
Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with
PO-3 Design/Development of
appropriate consideration for the public health and safety, And the
Solutions
cultural, societal, and environmental considerations.
Use research-based knowledge and research methods including
PO-4 Conduct Investigations design of experiments, analysis and interpretation of data, and
of Complex Problems synthesis of the information to provide valid conclusions.
Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and
PO-5 Modern Tool Usage
modeling to complex engineering activities with an understanding
of the limitations.
Apply reasoning informed by the contextual knowledge to assess
PO-6 The Engineer and societal, health, safety, legal and cultural issues and the
Society consequent responsibilities relevant to the professional
engineering practice.
Understand the impact of the professional engineering solutions
PO-7 Environment and in societal and environmental contexts, and demonstrate the
Sustainability knowledge of, and need for sustainable development.
Apply ethical principles and commit to professional ethics and
PO-8 Ethics responsibilities and norms of the engineering practice.
Function effectively as an individual, and as a member or leader in
PO-9 Individual and Team diverse teams, and in multidisciplinary settings.
Work
Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as,
PO-10 Communication being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive
Clear instructions.
Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a
PO-11 Project Management
member and leader in a team, to manage projects and in
and Finance
Multidisciplinary environments.
Recognize the need for, and have the preparation and ability to
PO-12 Life-long Learning engage in independent and life-long learning in the broadest
context of technological change.

ii
DATA STRUCTURES LABORATORY [BCSL305]

Course Learning Outcomes


At the end of the course, the student will be able to

1. Analyze and Compare various linear and non-linear data structures.


2. Demonstrate the working nature of different types of data structures and their applications.
3. Develop, analyze and evaluate the searching and sorting algorithms.
4. Choose the appropriate data structure for solving real world problems.

Department of Computer Science & Engineering. 2


DATA STRUCTURES LABORATORY [BCSL305]

List of Programs
Sl. No Program Description Page
No.
1 Develop a Program in C for the following: 5
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 (A integer), 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.
2 Develop and Implement a Program in C for the following operations on Strings 8
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
3 Design, Develop and Implement a menu driven Program in C for the following 10
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
4 Design, Develop and Implement a Program in C for converting an Infix Expression to 15
Postfix Expression. Program should support for both parenthesized and free
parenthesized expressions with the operators: +, -, *,/, %(Remainder), ^(Power) and
alphanumeric operands
5 Design, Develop and Implement a Program in C for the following Stack Applications 17
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^.
b. Solving Tower of Hanoi problem with n disks.
6 Design, Develop and Implement a menu driven Program in C for the following 20
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
7 Design, Develop and Implement a menu driven Program in C for the following 24
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 and Deletion at End of SLL
d. Perform Insertion and Deletion at Front of SLL
e. Demonstrate how this SLL can be used as STACK and QUEUE
f. Exit

Department of Computer Science & Engineering. 3


DATA STRUCTURES LABORATORY [BCSL305]

8 Design, Develop and Implement a menu driven Program in C for the following 31
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 sing 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
9 Design, Develop and Implement a Program in C for the following operations on Singly 38
Circular Linked List (SCLL) with header nodes
Represent and Evaluate a Polynomial
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
the above operations
10 Design, Develop and Implement a menu driven Program in C for the following 44
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. Delete an element(ELEM) from BST
e. Exit
11 Design, Develop and Implement a Program in C for the following operations on Graph(G) 50
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 BFS method
12 Given a File of N employee records with a set K of Keys(4-digit) which uniquely determine 54
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.

Department of Computer Science & Engineering. 4


DATA STRUCTURES LABORATORY [BCSL305]

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 (A integer), 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.

#include<stdio.h>
#include<stdlib.h>
struct Day
{
char *dayname;
int date;
char *activity;
};

void create(struct Day *day)


{
day dayName =(char *)malloc(sizeof(char)*20);
dayactivity=(char*)malloc(sizeof(char)*100);
printf(“Enter the day name:”);
scanf(“%s”, day->dayname);
printf(“Enter the date:”);
scanf(“%s”, &day->date);
printf(“Enter the activity for that day :”);
scanf(“%s”, day->activity);
}

// Function to read data from the keyboard


void read(struct Day *calendar, int size)
{
int i;
for(i=0; i<size;i++)
{
printf(“Enter details for the Day %d : \n”,i+1);
create(&calendar[i] );
}
}
// Function to display the calendar
void display(struct Day *calendar, int size)
{
int i;
printf(“Weekly activity details :\n”);
for(i=0; i <size;i++)
{
printf(“Day %d :\n”,i+1);
printf(“Day Name :%s\n”, calendar[i].dayname);
printf(“Date:%d\n”, calendar[i].date);
printf(Activity:%s\n”, calendar[i].activity);

7
DATA STRUCTURES LABORATORY [BCSL305]

printf(“\n”);
}
}

void freememory(struct Day *calendar, int size)


{
int i;
for(i=0;i<size;i++)
{
free(calendar[i].dayname);
free(calendar[i].activity);
}
}
int main()
{
int size;
printf(“Enter the number of days in the week :”);
scanf(“%d”, &size);

// Declare a calendar as an array of 7 elements


struct Day *calendar = (struct Day*)malloc(sizeof(struct Day)*size);

// Check if memory allocation is successful


if(calendar = = NULL)
{
printf(“Memory allocation failed \n”);
exit(0);
}
// Use the create function to initialize the calendar
read(calendar, size);

// Display the calendar


display(calendar, size);

// Free dynamically allocated memory


freeMemory(calendar, size);
free(calendar);
return 0;
}

7
DATA STRUCTURES LABORATORY [BCSL305]

Output

Enter the number of days in the week: 3

Enter details for the Day: 1


Enter the day name: Monday
Enter the Date: 02
Enter the activity for that day: class

Enter details for the Day: 2


Enter the day name: Tuesday
Enter the Date: 03
Enter the activity for that day: DSLAB

Enter details for the Day: 3


Enter the day name: Wednesday
Enter the Date: 04
Enter the activity for that day: Clubactivitry

Weekly activity details:


Day : 1
Day Name : Monday
Date : 02
Activity : class
Day : 2
Day Name : Tuesday
Date : 03
Activity : DSLAB
Day : 3
Day Name : Wednesday
Date : 04
Activity : Clubactivity

Department of Computer Science & Engineering. 7


DATA STRUCTURES LABORATORY [BCSL305]

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.
#include #include //Declarations char str[100], pat[50], rep[50], ans[100]; int i, j, c, m, k, flag=0;
#include<stdio.h>
#include<conio.h>
//Declarations
char str[100], pat[50], rep[50], ans[100];
int i, j, c, m, k, flag=0;

void stringmatch()
{
i = m = c = j = 0;
while(str[c] ! = '\0')
{
if(str[m] = = pat[i]) // ...... matching
{
i++; m++;
if(pat[i] = = '\0') //.....found occurrences.
{
flag = 1;
//.... copy replace string in ans string.
for(k = 0; rep[k] != '\0'; k++, j++)
ans[j] = rep[k];
i = 0;
c = m;
}
} // if ends.
else //... mismatch
{
ans[j] = str[c];
j++;
c++;
m = c;
i = 0;
}//else ends
} //end of while
ans[j] = '\0';
} //end stringmatch()

void main()
{
clrscr();
printf("\nEnter a main string \n");
gets(str);
printf("\nEnter a pattern string \n");
flushall();

Department of Computer Science & Engineering. 8


DATA STRUCTURES LABORATORY [BCSL305]

gets(pat);
printf("\nEnter a replace string \n");
flushall();
gets(rep);
stringmatch();
if(flag = = 1)
printf("\nThe resultant string is\n %s" , ans);
else
printf("\nPattern string NOT found\n");
getch();
} // end of main

SAMPLE OUTPUT:
RUN 1:
Enter a main string
Test
Enter a pattern string
Te
Enter a replace string
Re
The resultant string is
Rest
RUN 2:
Enter a main string
This is Data Structure lab
Enter a pattern string
Data Structure
Enter a replace string
Data structure with C
The resultant string is
This is Data structure with C lab
RUN 3:
Enter a main string
This is Data Structure lab
Enter a pattern string
Date
Enter a replace string
DATA
Pattern string NOT found

Department of Computer Science & Engineering. 9


DATA STRUCTURES LABORATORY [BCSL305]

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

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define max_size 5
int stack[max_size],top=-1;
void push();
void pop();
void display();
void pali();
int main()
{
int choice;
while(choice)
{
//printf("\n");
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:

Department of Computer Science & Engineering. 10


DATA STRUCTURES LABORATORY [BCSL305]

push();
break;
case 2:
pop();
break;
case 3:
pali();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
default:
printf("\nInvalid hoice:\n");
break;
}
}
return 0;
}
void push() //Inserting element into the stack
{
int item,n;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)

{
printf("Stack Underflow:");

Department of Computer Science & Engineering. 11


DATA STRUCTURES LABORATORY [BCSL305]

}
else
{
item=stack[top];
top=top-1;
printf("\nThe poped element: %d\t",item);
}
}
void pali()
{
int digit,j,k,len=top+1,flag=0,ind=0;
int num[len],rev[len],i=0;
while(top!=-1)
{
digit= stack[top];
num[i]=digit;
top--;
i++;
}
for(j=0;j<len;j++)
{
printf("Numbers= %d\n",num[j]);
}

printf("reverse operation : n");


for(k=len-1;k>=0;k--)
{
rev[k]=num[ind];
ind++;
}
printf("reverse array : );
for(k=0;k<len;k++)
{
printf("%d\n",rev[k]);
}

printf("check for palindrome \n");


int length = 0;

Department of Computer Science & Engineering. 12


DATA STRUCTURES LABORATORY [BCSL305]

for(i=0;i<len;i++)
{
if(num[i]==rev[i])
{
length = length+1;
}
}
if(length==len)
{
printf("It is palindrome number\n");
}
else
{
printf("It is not a palindrome number\n");
}
top = len-1;
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}
else
{
printf("\nThe stack elements are:\n"
); for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}

Department of CSE, KLECET, Chikodi. 13

Department of Computer Science & Engineering. 13


DATA STRUCTURES LABORATORY [BCSL305]

Output

--------STACK OPERATIONS-----------
1.Push
2.Pop
3.Palindrome
4.Display
5.Exit
-----------------------
Enter your choice: 1
Enter the element to be inserted: 1
Enter your choice: 1
Enter the element to be inserted: 2
Enter your choice: 1
Enter the element to be inserted: 1
Enter your choice: 1
Enter the element to be inserted: 5
Enter your choice: 2
The poped element: 5

Enter your choice: 4


The stack elements are:
121
Enter your choice: 3
Numbers= 1
Numbers= 2
Numbers= 1 reverse
operation : reverse
array : 1
2
1
Check for palindrome:
It is palindrome number

Department of Computer Science & Engineering. 14


DATA STRUCTURES LABORATORY [BCSL305]

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.

#define SIZE 50 /* Size of Stack


*/ #include <ctype.h>
#include <stdio.h>
char s[SIZE];
int top = -1; /* Global declarations */
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;
}
}

Department of Computer Science & Engineering. 15


DATA STRUCTURES LABORATORY [BCSL305]

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);
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 Postfix Expn: %s\n", infx, pofx);
}

Output

Read the Infix Expression ? (a+b)*c/d^5%1


Given Infix Expn: (a+b)*c/d^5%1 Postfix Expn: ab+c*d5^/1%

Department of Computer Science & Engineering. 16


DATA STRUCTURES LABORATORY [BCSL305]

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

// Evaluation of Suffix Expression


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define MAX 50
int stack[MAX];
char post[MAX];
int top=-1;
void pushstack(int tmp);
void calculator(char c);
void main()
{
int i;
printf("Insert a postfix notation :: ");
//gets(post);
scanf("%s",post);
for(i=0;i<strlen(post);i++)
{
if(post[i]>='0' && post[i]<='9')
{
pushstack(i);
}
if(post[i]=='+' || post[i]=='-' || post[i]=='*' || post[i]=='/' || post[i]=='^')
{
calculator(post[i]);
}
}
printf("\n\nResult :: %d",stack[top]);
}

void pushstack(int tmp)


{
top++;
stack[top]=(int)(post[tmp]-48);
}

Department of Computer Science & Engineering. 17


DATA STRUCTURES LABORATORY [BCSL305]

void calculator(char c)
{
int a,b,ans;
a=stack[top];
stack[top]='\0';
top--;
b=stack[top];
stack[top]='\0';
top--;
switch(c)
{
case '+':
ans=b+a;
break;
case '-':
ans=b-a;
break;
case '*':
ans=b*a;
break;
case '/':
ans=b/a;
break;
case '^':
ans=pow(b,a);
break;
default:
ans=0;
}
top++;
stack[top]=ans;
}
// Towers of
Hanoi #include
<stdio.h>
void towers(int, char, char,char);
int main()
{
int num;
printf("Enter the number of disks :");
scanf("%d", &num);

Department of Computer Science & Engineering. 18


DATA STRUCTURES LABORATORY [BCSL305]

printf("The sequence of moves involved in the Tower of Hanoi are :\n");


towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c",
frompeg, topeg); return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}

Output

Enter the number of disks : 3


The sequence of moves involved in the Tower of Hanoi are :
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

Department of Computer Science & Engineering. 19


DATA STRUCTURES LABORATORY [BCSL305]

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

#include<stdio.h>
#include<stdlib.h>
#define max 10
int q[10],front=0,rear=-1;
void main()
{
int ch;
void insert();
void delet();
void display();
printf("\nCircular Queue operations\n");
printf("1.insert\n2.delete\n3.display\n4.exit\n");
while(1)
{
printf("Enter your
choice:"); scanf("%d",&ch);
switch(ch)
{
case 1: insert();
break;
case 2: delet();
break;
case 3: display();
break;
case 4: exit(1);
default: printf("Invalid option\n");
}
}
}

Department of Computer Science & Engineering. 20


DATA STRUCTURES LABORATORY [BCSL305]

void insert()
{
int x;
if((front==0&&rear==max-1)||(front>0&&rear==front-1))
printf("Queue is overflow\n");
else
{
printf("Enter element to be insert:");
scanf("%d",&x);
if(rear==max-1&&front>0)
{
rear=0;
q[rear]=x;
}
else
{
if((front==0&&rear==-1)||(rear!=front-1))
q[++rear]=x;
}
}
}
void delet()
{
int a;
if((front==0)&&(rear==-1))
{
printf("Queue is underflow\n");
exit(1);
}
if(front==rear)
{
a=q[front];
rear=-1;
front=0;
}
else
if(front==max-1)
{
a=q[front];
front=0;
}
else a=q[front++];

Department of Computer Science & Engineering. 21


DATA STRUCTURES LABORATORY [BCSL305]

printf("Deleted element is:%d\n",a);


}

void display()
{
int i,j;
if(front==0&&rear==-1)
{
printf("Queue is underflow\n");
exit(1);
}
if(front>rear)
{
for(i=0;i<=rear;i++)
printf("\t%d",q[i]);
for(j=front;j<=max-1;j++)
printf("\t%d",q[j]);
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]);
}
else
{
for(i=front;i<=rear;i++)
{
printf("\t%d",q[i]);
}
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]);
}
printf("\n");
}

Department of Computer Science & Engineering. 22


DATA STRUCTURES LABORATORY [BCSL305]

Output

Circular Queue operations


1.insert
2.delete
3.display
4.exit
Enter your choice:1
Enter element to be insert:10

Enter your choice:1


Enter element to be insert:20

Enter your choice:1


Enter element to be insert:30

Enter your choice:3


10 20 30
rear is at 30

front is at 10

Enter your choice:2


Deleted element is:10

Enter your choice:3


20 30
rear is at 30

front is at 20
Enter your choice:4

Department of Computer Science & Engineering. 23


DATA STRUCTURES LABORATORY [BCSL305]

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 and Deletion at End of SLL d. Perform
Insertion and Deletion at Front of SLL
e. Demonstrate how this SLL can be used as STACK and QUEUE f.
Exit

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int count=0;
struct node
{
int sem,phno;
char name[20],branch[10],usn[20];
struct node *next;
}*first=NULL,*last=NULL,*temp=NULL,
*temp1; void create()
{
int sem,phno;
char name[20],branch[10],usn[20];
temp=(struct node*)malloc(sizeof(struct node));
printf("\n Enter usn,name, branch, sem, phno of student : ");
scanf("%s %s %s %d %d", usn, name,branch, &sem,&phno);
strcpy(temp->usn,usn);
strcpy(temp->name,name);
strcpy(temp->branch,branch);
temp->sem = sem;
temp->phno = phno;
temp->next=NULL;
count++;
}

Department of Computer Science & Engineering. 24


DATA STRUCTURES LABORATORY [BCSL305]

void insert_atfirst()
{
if (first == NULL)
{
create();

first = temp;
last = first;
}
else
{
create();
temp->next = first;
first = temp;
}
}

void insert_atlast()
{
if(first==NULL)
{
create();
first = temp;
last = first;
}
else
{
create();
last->next =temp;
last = temp;
}
}
void display()
{
temp1=first;
if(temp1 == NULL)
{
printf("List empty to display \n");
return;
}

Department of Computer Science & Engineering. 25


DATA STRUCTURES LABORATORY [BCSL305]

printf("\n Linked list elements from begining : n");


while (temp1!= NULL)
{
printf("%s %s %s %d %d\n", temp1->usn, temp1->name,temp1->branch,temp1-
>sem, temp1->phno );
temp1 = temp1->next;
}
printf(" No of students = %d ", count);
}
int deleteend()
{
struct node *temp;
temp=first;
if(temp-next==NULL)
{
free(temp);
first=NULL;
}
else
{
while(temp->next!=last)
temp=temp->next;
printf("%s %s %s %d %d\n", last->usn, last->name,last->branch, last->sem, last->phno );
free(last);
temp-next=NULL;
last=temp;
}
count--;
return 0;
}
int deletefront()
{
struct node *temp;
temp=first;
if(temp->next==NULL)
{
free(temp);
first=NULL;
return 0;
}

Department of Computer Science & Engineering. 26


DATA STRUCTURES LABORATORY [BCSL305]

else
{
first=temp->next;
printf("%s %s %s %d %d", temp->usn, temp->name,temp->branch,temp->sem, temp->phno
); free(temp);
}
count--;
return 0;
}
void main()
{
int ch,n,i;
first=NULL;
temp = temp1 = NULL;
printf("----------------- MENU---------------------- \n");
printf("\n 1 – create a SLL of n emp");
printf("\n 2 - Display from beginning");
printf("\n 3 - Insert at end");
printf("\n 4 - delete at end");
printf("\n 5 - Insert at beg");
printf("\n 6 - delete at beg");
printf("\n 7 - exit\n");
printf("------------------------------------------- \n");
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\n Enter no of students : ");
scanf("%d", &n);
for(i=0;i<n;i++)
insert_atfirst();
break;
case 2:
display();
break;
case 3:

Department of Computer Science & Engineering. 27


DATA STRUCTURES LABORATORY [BCSL305]

insert_atlast();
break;
case 4:

deleteend();
break;
case 5:
insert_atfirst();
break;
case 6:
deletefront();
break;
case 7:
exit(0);
default: printf("wrong choice\n");
}
}
}

Department of Computer Science & Engineering. 28


DATA STRUCTURES LABORATORY [BCSL305]

Output

–---------------MENU----------------------
1 create a SLL of n emp
2 Display from beginning
3 Insert at end
4 delete at end
5 Insert at beg
6 delete at beg
7 exit
------------------------------------------------

Enter choice : 1
Enter no of students : 2
Enter usn,name, branch, sem, phno of student : 007 vijay CSE 3 121
Enter usn,name, branch, sem, phno of student : 100 yashas CSE 3 911

Enter choice : 2
Linked list elements from begining :
100 yashas CSE 3 911
007 vijay CSE 3 121

No of students = 2

Enter choice : 3
Enter usn,name, branch, sem, phno of student : 001 raj CSE 3 111

Enter choice : 2
Linked list elements from begining :
100 yashas CSE 3 911
007 vijay CSE 3 121
001 raj CSE 3 111
No of students = 3
Enter choice : 4
001 raj CSE 3 111
Enter choice : 2

Department of Computer Science & Engineering. 29


DATA STRUCTURES LABORATORY [BCSL305]

Linked list elements from begining :


100 yashas CSE 3 911
007 vijay CSE 3 121
No of students = 2

Enter choice : 5
Enter usn,name, branch, sem, phno of student : 003 harsh cse 3 111

Enter choice : 2
Linked list elements from begining :
003 harsh cse 3 111
100 yashas CSE 3 911
007 vijay CSE 3 121
No of students = 3

Enter choice : 6 003


harsh cse 3 111

Enter choice : 2
Linked list elements from begining :
100 yashas CSE 3 911
007 vijay CSE 3 121
No of students = 2

Enter choice : 7

Department of Computer Science & Engineering. 30


DATA STRUCTURES LABORATORY [BCSL305]

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

#include<string.h>
int count=0;
struct node
{
struct node *prev;
int ssn,phno;
float sal;
char name[20],dept[10],desg[20];
struct node *next;
}*h,*temp,*temp1,*temp2,*temp4;

void create()
{
int ssn,phno;
float sal;
char name[20],dept[10],desg[20];
temp =(struct node *)malloc(sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
printf("\n Enter ssn,name,department, designation, salary and phno of employee : ");
scanf("%d %s %s %s %f %d", &ssn, name,dept,desg,&sal, &phno);
temp->ssn = ssn;
strcpy(temp->name,name);
strcpy(temp->dept,dept);
strcpy(temp->desg,desg);
temp->sal = sal;

Department of Computer Science & Engineering. 31


DATA STRUCTURES LABORATORY [BCSL305]

temp->phno = phno;
count++;
}
void insertbeg()
{
if (h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp->next = h;
h->prev = temp;
h = temp;
}
}
void insertend()
{
if(h==NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp1->next = temp;
temp->prev = temp1;
temp1 = temp;
}
}
void displaybeg()
{
temp2 =h;
if(temp2 == NULL)

Department of Computer Science & Engineering. 32


DATA STRUCTURES LABORATORY [BCSL305]

{
printf("List empty to display \n");
return;
}
printf("\n Linked list elements from begining :
\n"); while (temp2!= NULL)
{
printf("%d %s %s %s %f %d\n", temp2->ssn, temp2->name,temp2->dept,temp2->desg,
temp2->sal, temp2->phno );
temp2 = temp2->next;
}
printf(" No of employees = %d ", count);
}
int deleteend()
{
struct node *temp;
temp=h;
if(temp->next==NULL)
{
free(temp);
h=NULL;
return 0;
}
else
{
temp2=temp1->prev;
temp2->next=NULL;
printf("%d %s %s %s %f %d\n", temp1->ssn, temp1->name,temp1->dept, temp1->desg,
temp1->sal, temp1->phno );
free(temp1);
}
count--;
return 0;
}

int deletebeg()
{
struct node *temp; temp=h;
if(temp->next==NULL)

Department of Computer Science & Engineering. 33


DATA STRUCTURES LABORATORY [BCSL305]

{
free(temp);
h=NULL;
}
else
{
h=h->next;
printf("%d %s %s %s %f %d", temp->ssn, temp->name,temp->dept, temp-
>desg, temp->sal, temp->phno );
free(temp);
}
count--;
return 0;
}
void main()
{
int ch,n,i;
h=NULL;
temp = temp1 = NULL;
printf("----------------- MENU-------------------- \n");
printf("\n 1 – create a DLL of n emp");
printf("\n 2 - Display from beginning");
printf("\n 3 - Insert at end");
printf("\n 4 - delete at end");
printf("\n 5 - Insert at beg");
printf("\n 6 - delete at beg");
printf("\n 7 - exit\n");
printf("------------------------------------------ \n");
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\n Enter no of employees : ");
scanf("%d", &n);
for(i=0;i<n;i++)
insertend();
break;

Department of Computer Science & Engineering. 34


DATA STRUCTURES LABORATORY [BCSL305]

case 2:
displaybeg();
break; case
3:
insertend();
break; case
4:
deleteend();
break;

case 5:
insertbeg();
break; case
6:
deletebeg();
break;
case 7:
exit(0);
default: printf("wrong choice\n");
}
}
}

Department of Computer Science & Engineering. 35


DATA STRUCTURES LABORATORY [BCSL305]

Output

MENU
1. Create a DLL of n emp
2. Display from beginning
3. Insert at end
4. Delete at end
5. Insert at beg
6. Delete at beg
7. Exit
-----------------------------
Enter choice : 1
Enter no of employees : 2
Enter ssn,name,department, designation, salary and phno of employee :

1 RAJ SALES MANAGER 15000 911


Enter ssn,name,department, designation, salary and phno of employee :

2 RAVI HR ASST 10000 123

Enter choice : 2
Linked list elements from begining :
1 RAJ SALES MANAGER 15000.000000 911
2 RAVI HR ASST 10000.000000
123 No of employees = 2
Enter choice : 3
Enter ssn,name,department, designation, salary and phno of
employee : 3 RAM MARKET MANAGER 50000 111

Enter choice : 2
Linked list elements from begining :
1 RAJ SALES MANAGER 15000.000000 911
2 RAVI HR ASST 10000.000000 123
3 RAM MARKET MANAGER 50000.000000 111
No of employees = 3
Enter choice : 4
3 RAM MARKET MANAGER 50000.000000 111

Department of Computer Science & Engineering. 36


DATA STRUCTURES LABORATORY [BCSL305]

Enter choice : 2
Linked list elements from begining :
1 RAJ SALES MANAGER 15000.000000 911
2 RAVI HR ASST 10000.000000
123 No of employees = 2

Enter choice : 5
Enter ssn,name,department, designation, salary and phno of employee
: 0 ALEX EXE TRAINEE 2000 133
Enter choice : 2
Linked list elements from begining :
0 ALEX EXE TRAINEE 2000.000000 133
1 RAJ SALES MANAGER 15000.000000 911
2 RAVI HR ASST 10000.000000
123 No of employees = 3

Enter choice : 6
0 ALEX EXE TRAINEE 2000.000000 133

Enter choice : 2
Linked list elements from begining :

1 RAJ SALES MANAGER 15000.000000 911


2 RAVI HR ASST 10000.000000 123

No of employees = 2
Enter choice : 7
Exit

Department of Computer Science & Engineering. 37


DATA STRUCTURES LABORATORY [BCSL305]

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

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<math.h>
typedef struct node
{
int expo,coef;
struct node *next;
}node;
node * insert(node *,int,int);
node * create();
node * add(node *p1,node *p2);
int eval(node *p1);
void display(node *head);
node *insert(node*head,int expo1,int coef1)
{
node *p,*q;
p=(node *)malloc(sizeof(node));
p->expo=expo1;
p->coef=coef1;
p->next=NULL;
if(head==NULL)
{
head=p;
head->next=head;
return(head);
}
if(expo1>head->expo)
{
p->next=head->next;
head->next=p;

Department of Computer Science & Engineering. 38


DATA STRUCTURES LABORATORY [BCSL305]

head=p;
return(head);
}
if(expo1==head->expo)
{
head->coef=head->coef+coef1;
return(head);
}
q=head;
while(q->next!=head&&expo1>=q->next->expo)
q=q->next;
if(p->expo==q->expo)
q->coef=q->coef+coef1;
else
{
p->next=q->next;
q->next=p;
}
return(head);
}
node *create()
{
int n,i,expo1,coef1;
node *head=NULL;
printf("\n\nEnter no of terms of
polynomial==>"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter coef & expo==>");
scanf("%d%d",&coef1,&expo1);
head=insert(head,expo1,coef1);
}
return(head);
}
node *add(node *p1,node *p2)
{
node *p;
node *head=NULL;
printf("\n\n\nAddition of polynomial==>");

Department of Computer Science & Engineering. 39


DATA STRUCTURES LABORATORY [BCSL305]

p=p1->next;
do
{
head=insert(head,p->expo,p->coef);
p=p->next;
}
while(p!=p1->next);
p=p2->next;
do
{
head=insert(head,p->expo,p->coef);
p=p->next;
}
while(p!=p2->next);
return(head);
}
int eval(node *head)
{
node *p;
int x,ans=0;
printf("\n\nEnter the value of x=");
scanf("%d",&x);
p=head->next;
do
{
ans=ans+p->coef*pow(x,p->expo);
p=p->next;
}
while(p!=head->next);
return(ans);
}
void display(node *head)
{
node *p,*q;
int n=0;
q=head->next;
p=head->next;
do
{

Department of Computer Science & Engineering. 40


DATA STRUCTURES LABORATORY [BCSL305]

n++;
q=q->next;
}
while(q!=head->next);
printf("\n\n\tThe polynomial is==>");
do
{
if(n-1)
{
printf("%dx^(%d) + ",p->coef,p->expo);
p=p->next;
}
else
{
printf(" %dx^(%d)",p->coef,p->expo);
p=p->next;
}
n--;
}
while(p!=head->next);
}
void main()
{
int a,x,ch;
node *p1,*p2,*p3;
p1=p2=p3=NULL;
while(1)
{
printf("\n\t---------------- << MENU >>---------------
"); printf("\n\tPolynomial Operations :");
printf(" 1.Add");
printf("\n\t\t\t\t2.Evaluate");
printf("\n\t\t\t\t3.Exit");
printf("\n\t------------------------------------------- ");
printf("\n\n\n\tEnter your choice==>");
scanf("%d",&ch);
switch(ch)
{
case 1 :
p1=create();

Department of Computer Science & Engineering. 41


DATA STRUCTURES LABORATORY [BCSL305]

display(p1);
p2=create();
display(p2);
p3=add(p1,p2);
display(p3);
break;
case 2 :
p1=create();
display(p1);
a=eval(p1);
printf("\n\nValue of polynomial=%d",a);
break;
case 3 :
exit(0);
break;
default :
printf("\n\n\tinvalid choice");
break;
}
}
}

Department of Computer Science & Engineering. 42


DATA STRUCTURES LABORATORY [BCSL305]

Output
-----------------<< MENU >>---------------
Polynomial Operations : 1.Add
2.Evaluate
3.Exit
---------------------------------------------------
Enter your choice==>1
Enter no of terms of polynomial==>3
Enter coef & expo==>
4
3
Enter coef & expo==>
22

Enter coef & expo==>


51
The polynomial is==>5x^(1) + 2x^(2) +
4x^(3) Enter no of terms of polynomial==>3
Enter coef & expo==>
41
Enter coef & expo==>
3
2
Enter coef & expo==>
53
The polynomial is==>4x^(1) + 3x^(2) + 5x^(3)
Addition of polynomial==>
The polynomial is==>9x^(1) + 5x^(2) +
9x^(3) Enter your choice==>2
Enter no of terms of polynomial==>3
Enter coef & expo==>
3
1
Enter coef & expo==>
42
Enter coef & expo==>
54
The polynomial is==>3x^(1) + 4x^(2) +
5x^(4) Enter the value of x=2
Value of
polynomial=102 Enter
your choice==>3 exit

Department of Computer Science & Engineering. 43


DATA STRUCTURES LABORATORY [BCSL305]

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,
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. Delete an element(ELEM) from BST
e. Exit

# include <stdio.h>
# include <stdlib.h>
int flag=0;
typedef struct BST
{
int data;
struct BST *lchild, *rchild;
}
node;
void insert(node *, node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *, int, node **);

void main()
{
int choice;
int ans =1;
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
printf("\nProgram For Binary Search Tree ");
do {
printf("\n1.Create");
printf("\n2.Search");
printf("\n3.Recursive
Traversals"); printf("\n4.Exit");

Department of Computer Science & Engineering. 44


DATA STRUCTURES LABORATORY [BCSL305]

printf("\nEnter your choice :");


scanf("%d", &choice);
switch (choice)
{
case 1:
do {
new_node = get_node();
printf("\nEnter The Element ");
scanf("%d", &new_node->data);

if (root == NULL) /* Tree is not Created


*/ root = new_node;
else
insert(root, new_node);

printf("\nWant To enter More Elements?(1/0)");


scanf("%d",&ans);
} while (ans);
break;

case 2:
printf("\nEnter Element to be searched :");
scanf("%d", &key);
tmp = search(root, key, &parent);
if(flag==1)
{
printf("\nParent of node %d is %d", tmp->data, parent->data);
}
else
{
printf("\n The %d Element is not Present",key);
}
flag=0;
break;
case 3:
if (root == NULL)
printf("Tree Is Not Created");
else {
printf("\nThe Inorder display : ");
inorder(root);

Department of Computer Science & Engineering. 45


DATA STRUCTURES LABORATORY [BCSL305]

printf("\nThe Preorder display : ");


preorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
}
} while (choice != 4);
}
/*Get new Node */
node *get_node()
{ node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*This function is for creating a binary search tree */
void insert(node *root, node *new_node)
{
if (new_node->data < root->data)
{
if(root->lchild == NULL)
root->lchild = new_node;
else
insert(root->lchild, new_node);
}

if (new_node->data > root->data)


{
if (root->rchild == NULL) root->rchild = new_node;
else
insert(root->rchild, new_node);
}
}
/*This function is for searching the node from binary Search
Tree*/ node *search(node *root, int key, node **parent)
{
node *temp;
temp = root;
while (temp != NULL)

Department of Computer Science & Engineering. 46


DATA STRUCTURES LABORATORY [BCSL305]

{
if (temp->data == key) {
printf("\nThe %d Element is Present", temp->data);
flag=1;
return temp;
}
*parent = temp;

if (temp->data > key)


temp = temp->lchild;
else
temp = temp->rchild;
}
return NULL;
}
/*
This function displays the tree in inorder fashion
*/
void inorder(node *temp)
{
if (temp != NULL)
{
inorder(temp->lchild);
printf("%d\t", temp->data);
inorder(temp->rchild);
}
}
/*
This function displays the tree in preorder
fashion */
void preorder(node *temp)
{
if (temp != NULL)
{
printf("%d\t", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}

Department of Computer Science & Engineering. 47


DATA STRUCTURES LABORATORY [BCSL305]

/*This function displays the tree in postorder fashion */


void postorder(node *temp)
{
if (temp != NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d\t", temp->data);
}
}

Output

Program For Binary Search Tree


1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice :1
Enter The Element 15
Want To enter More Elements?(1/0)1
Enter The Element 25

Want To enter More Elements?(1/0)1


Enter The Element 35

Want To enter More Elements?(1/0)1


Enter The Element 45

Want To enter More Elements?(1/0)1


Enter The Element 5
Want To enter More Elements?(1/0)1
Enter The Element 7

Want To enter More Elements?(1/0)0

Department of Computer Science & Engineering. 48


DATA STRUCTURES LABORATORY [BCSL305]

Enter your choice :2


Enter Element to be searched :7

The 7 Element is Present


Parent of node 7 is 5
1.Create
2.Search
3.Recursive Traversals
4.Exit

Enter your choice :2


Enter Element to be searched :88
The 88 Element is not Present

Enter your choice :3

The Inorder display : 5 7 15 25 35 45


The Preorder display : 15 5 7 25 35 45
The Postorder display : 7 5 45 35 25 15

Enter your choice :4

Department of Computer Science & Engineering. 49


DATA STRUCTURES LABORATORY [BCSL305]

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 BFS method
c. Check whether a given graph is connected or not using DFS method

#include <stdio.h>
#include <stdlib.h>
int a[20][20],q[20],visited[20],reach[10],n,i,j,f=0,r=-1,count=0;
void bfs(int v)
{
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
{
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
count++;
dfs(i);
}
}
}
void main()
{
int v, choice;
printf("\n Enter the number of vertices:");
scanf("%d",&n);

Department of Computer Science & Engineering. 50


DATA STRUCTURES LABORATORY [BCSL305]

for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
for(i=1;i<=n-1;i++)
reach[i]=0;
printf("\n Enter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]); printf("1.BFS\n 2.DFS\n 3.Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
if((v<1)||(v>n))
{
printf("\n Bfs is not possible");
}
else
{
printf("\n The nodes which are reachable from %d:\n",v);
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
}
break;
case 2:dfs(1);
if(count==n-1)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
break;
case 3: exit(0);
}}

Department of Computer Science & Engineering. 51


DATA STRUCTURES LABORATORY [BCSL305]

Output

Enter the number of vertices:5


Enter graph data in matrix form:
01010101010101010
10001000
1.BFS
2.DFS
3.Exit
2

1->2
2->3
3->4
2->5
Graph is connectedcsdept
Enter the number of vertices:5
Enter graph data in matrix form:
01010101000101010
10000000
1.BFS
2.DFS
3.Exit
2
1->2
2->3
3->4
Graph is not connected
Enter the number of vertices:5

Department of Computer Science & Engineering. 52


DATA STRUCTURES LABORATORY [BCSL305]

Enter graph data in matrix form:


01100000100000000
10000100
1.BFS
2.DFS
3.Exit
1
Enter the starting vertex:1
The nodes which are reachable from
1: 2 3 4

Enter graph data in matrix form:


01100000100000000
10000100
1.BFS
2.DFS
3.Exit
1
Enter the starting vertex:0
BFS is not possible

Department of Computer Science & Engineering. 53


DATA STRUCTURES LABORATORY [BCSL305]

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

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int create(int);
void linear_prob(int[], int, int);
void display (int[]);
void 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);
display(a);
}

Department of Computer Science & Engineering. 54


DATA STRUCTURES LABORATORY [BCSL305]

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");
i=0;
while(i<MAX)
{
if (a[i]!=-1)
count++;
i++;
}
printf("Collision avoided successfully using LINEAR
PROBING\n"); if(count == MAX)
{
printf("\n Hash table is full");
display(a);
exit(1);
}
for(i=key+1; i<MAX; i++)
if(a[i] == -1)
{
a[i] = num;
flag =1;
break;
}

Department of Computer Science & Engineering. 55


DATA STRUCTURES LABORATORY [BCSL305]

//for(i=0;i<key;i++)
i=0;
while((i<key) && (flag==0))
{
if(a[i] == -1)
{
a[i] = num;
flag=1;
break;
}
i++;
}
}
}
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
{
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;
}
}
}

Department of Computer Science & Engineering. 56


DATA STRUCTURES LABORATORY [BCSL305]

Output

collision handling by linear probing :


Enter the data1234
Do you wish to continue ? (1/0) 1
Enter the data2548
Do you wish to continue ? (1/0) 1
Enter the data3256
Do you wish to continue ? (1/0) 1
Enter the data1299
Do you wish to continue ? (1/0) 1
Enter the data1298
Do you wish to continue ? (1/0) 1
Enter the data1398
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 1398
34 1234
48 2548
56 3256
98 1298
99 1299

Department of Computer Science & Engineering. 57

You might also like