You are on page 1of 41

SRINIVAS INSTITUTE OF TECHNOLOGY

(Affiliated to Visvesvaraya Technological University, Belagavi)


(Accredited by NAAC)
Valachil, Mangaluru-574143

Department of Information Science and Engineering

LAB MANUAL
DATA STRUCTURES LABORATORY
BCSL305

3rd Semester B.E.


2023 - 2024

Name:

USN:

Section:

Batch:

Compiled By: Prof. Sowmya, Assistant Professor


Srinivas Institute of Technology
Vision

To be a premier institute of professional education and research, responsive


to the needs of industry and society.

Mission

To achieve academic excellence through innovative teaching- learning


practice, by providing conducive research environment, industry-institute
interaction and skill development, leading to professionals with ethical values
and social responsibilities.

Department of Information Science and Engineering


Vision

To be a centre of excellence in Information Science and Engineering with


quality education and research, responsive to the needs of industry and
society.

Mission

• To achieve academic excellence through innovative teaching-learning


practice.
• To inculcate the spirit of innovation, creativity and research.
• To enhance employability through skill development and industry-
institute interaction.
• To develop professionals with ethical values and social responsibilities.

Program Educational Objectives (PEOs)


Graduates will be

PEO1: Competent professionals with knowledge of Information Science &


Engineering to pursue variety of careers and higher education.
PEO2: Proficient in designing innovative solutions to real life problems that
are technically sound, economically viable and socially acceptable.
PEO3: Capable of working in teams, adapting to new technologies and
upgrading skills required to serve the society with ethical values.
14.09.2023

DATA STRUCTURES LABORATORY


SEMESTER – III

Course Code BCSL305 CIE Marks 50


Number of Contact Hours/Week 0:0:2 SEE Marks 50
Total Number of Lab Contact Hours 28 Exam Hours 03
Credits – 1
Course Learning Objectives:
This laboratory course enables students to get practical experience in design, develop, implement, analyze
and evaluation/testing of
● Dynamic memory management
● Linear data structures and their applications such as stacks, queues and lists
● Non-Linear data structures and their applications such as trees and graphs

Descriptions (if any):


● Implement all the programs in “C ” Programming Language and Linux OS.
Programs List:
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.

2. Develop 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.
3. Develop 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
14.09.2023

4. Develop 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.
5. Develop 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

6. Develop 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
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
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
9. Develop a Program in C for the following operationson 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
10. Develop a menu driven Program in C for the following operations on Binary Search Tree
(BST) of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
11. Develop a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS
method
14.09.2023

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.
Laboratory Outcomes: The student should be able to:

● Analyze various linear and non-linear data structures


● Demonstrate the working nature of different types of data structures and their applications
● Use appropriate searching and sorting algorithms for the give scenario.
● Apply the appropriate data structure for solving real world problems
Conduct of Practical Examination:
● Experiment distribution
o For laboratories having only one part: Students are allowed to pick one experiment from
the lot with equal opportunity.
o For laboratories having PART A and PART B: Students are allowed to pick one
experiment from PART A and one experiment from PART B, with equal opportunity.
● Change of experiment is allowed only once and marks allotted for procedure to be made zero of
the changed part only.
● Marks Distribution (Need to change in accordance with university regulations)
c) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 =
100 Marks
d) For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
ii. Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks
List of Programs

Sl No Program Description Page


Number
01 Calendar 2-4

02 Perform Pattern Matching Operation 4-5

03 Operations on STACK of Integers 6-8

04 Infix Expression to Postfix Expression. conversion 9-10

05 Evaluation of Suffix expression, Towers of Hanoi 11,12

06 Circular QUEUE operations 13-15

07 Singly Linked List (SLL) operations 15-17

08 Doubly Linked List (DLL) operations 18-20

09 Singly Circular Linked List (SCLL) with header nodes 21-24


operations.
10 Binary Search Tree (BST) operations 25-28

11 Operations on Graph 29-30

12 Linear probing on File with hashing 31-33

Internal Schedule:
Date
IA Test 1 2
Programs included 1-6 7-12
Data Structures Laboratory - 18CSL38 III Semester / B.E
EXPERIMENT – 01: Array operations
1. 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).
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Define the structure for a day


struct Day {
char *name; // Dynamically allocated string for the day name
int date; // Integer for the date
char *activity; // Dynamically allocated string for the activity description
};

int main() {
// Declare an array of 7 elements, each of type struct Day
struct Day calendar[7];

// Initialize each element of the array


for (int i = 0; i < 7; ++i) {
// Dynamically allocate memory for the day name and activity
calendar[i].name = (char *)malloc(50 * sizeof(char));
calendar[i].activity = (char *)malloc(100 * sizeof(char));
printf("Enter day name for Day %d: ", i + 1);
scanf("%s", calendar[i].name);
printf("Enter date for Day %d: ", i + 1);
scanf("%d", &calendar[i].date);
printf("Enter activity for Day %d: ", i + 1);
scanf(" %[^\n]s", calendar[i].activity); // Read the activity with spaces
}
printf("Calendar for the week:\n");
// Access and print information for each day
for (int i = 0; i < 7; ++i) {
printf("Day: %s\n", calendar[i].name);
printf("Date: %d\n", calendar[i].date);
printf("Activity: %s\n\n", calendar[i].activity);
}
// Free dynamically allocated memory
for (int i = 0; i < 7; ++i) {
free(calendar[i].name);
free(calendar[i].activity);
}
return 0;
}
Output
Calendar for the week:
Day: Monday
Dept. of ISE,SIT, Mangaluru Page|2
Data Structures Laboratory - 18CSL38 III Semester / B.E
Date: 1
Activity: Work from 9 AM to 5 PM

Day: Tuesday
Date: 2
Activity: Meeting at 10 AM

Day: Wednesday
Date: 3
Activity: Gym at 6 PM

Day: Thursday
Date: 4
Activity: Dinner with friends at 7 PM

Day: Friday
Date: 5
Activity: Movie night at 8 PM

Day: Saturday
Date: 6
Activity: Weekend getaway

Day: Sunday
Date: 7
Activity: Relax and recharge

Dept. of ISE,SIT, Mangaluru Page|3


Data Structures Laboratory - 18CSL38 III Semester / B.E

Program should be tested and output should be recorded

Display, Create- 3 elements, Display, Insert, Insert, Display, Insert

Additional Program:

➢ Input a word
➢ Insert new character at specified position and display the updated word
➢ Delete a character at specified position and display the updated word.
Evaluation of experiment: Conduction: 5, Modification: 5 Viva 4

EXPERIMENT – 02: Strings operations


Design, develop and Implement a program in C for the following
Stringsoperations
a. Read a Main String (STR), a Pattern String (PAT) and a Replace
b. String(REP).
c. Perform Pattern Matching Operation: Find and Replace all
d. occurrencesof PAT in STR with REP if PAT exists in STR.
e. Repost suitable messages incase PAT does not exist in STR.
f. Support the program with functions for each of the above operations. Do not use built-in functions.

Steps for Pattern_Match_Repace()


• For All characters of Main String STR, scan each
character of Main string STR and Pattern String PAT if
correspondingcharacter are same.
• If pattern found then replace all matching characters
by replacement string REP otherwise copy characters of
Main string till scanned position to resultant string
ANS.
• Reset next scanning position, point to first character
ofPAT and continue.

CODE:
#include<stdio.h>
#include<stdlib.h>
char STR[100], PAT[50], REP[50], ANS [100];
int Pattern_Match_Replace() { // String Matching function
int i=0; //index for PAT
int c=0, m=0; //index for STR
int k=0 ; //index for REP
int flag=0;
int j=0; //index for ANS

Dept. of ISE,SIT, Mangaluru Page|4


Data Structures Laboratory - 18CSL38 III Semester / B.E
while(STR[c] != '\0') {
if(STR[m] == PAT[i]){ //if same , scan next character
i++;
m++;
if(PAT[i] == '\0'){//If scanned then replace
flag = 1;
k=0;
while(REP[k] != '\0'){
ANS[j++] = REP[k++];
}
i = 0;
c = m;
}
}
else {
ANS[j++] = STR[c++]; // copy input string to resultant string if not matching
m = c;
i = 0; //reset index of pattern string to point to first char and scan again
}
} //end of while
ANS[j] = '\0';
return flag;
}

int main(){ //Main program


printf("\nEnter a main string :");
gets(STR);
printf("\nEnter a pattern string :");
gets(PAT);
printf("\nEnter a string to be replaced:");
gets(REP);
if(Pattern_Match_Replace( ) )
printf("\nThe resultant string is: %s \n" , ANS);
else
printf("\nPattern string NOT found\n");
return 0;
}
OUTPUT

Enter a main string: Data Structures Laboratory using C++


Enter a pattern string: C++
Enter a replace string: C
The resultant string is: Data Structures Laboratory using C

Find out any other efficient method for pattern matching

Dept. of ISE,SIT, Mangaluru Page|5


Data Structures Laboratory - 18CSL38 III Semester / B.E
EXPERIMENT – 03: STACK operations
Design, Developand Implement a menudrivenprogram in Cforthe following operations on STACK of integers
(Array implementation of stack with maximum size MAX)
a. Push an element onto stack
b. Pop an element fromstack.
c. Demonstrate howstackcanbeusedtocheckpalindrome.
d. DemonstrateOverflowandUnderflowsituationsonstack.
e. Displaythe statusofstack.
f. Exit.Supporttheprogramwithappropriatefunctionsforeach of the above operations.

PUSH operation:

• Display Stack overflow if no space in stack ie. TOP=MAX-1


• Otherwise Increment TOP and copy new ITEM at TOP

POP operation:

• Display Stack Underflow if no element in stack ie. TOP=-1


• Otherwise return the TOP element of stack and decrement TOP by 1

Palindrome check operation:

• Compare both end of stack till TOP/2 if all element are matching
then display Palindrome otherwise not a palindrome

CODE:
#include<stdio.h>
#include<stdlib.h>
#define MAX 5
void Display();
int stack[MAX],top = -1,i;
int isEmpty(){
if(top == -1){
printf("\nStack is Underflow!");
return 1; //return 1 if empty
}
else
return 0; //not empty
}
int isFull(){
if (top == (MAX-1)){
printf("\n\nStack is Overflow!");
return 1; //1 if full
}
else
return 0;//not full
}

Dept. of ISE,SIT, Mangaluru Page|6


Data Structures Laboratory - 18CSL38 III Semester / B.E

void Push(int item){ /*PUSH FUNCTION*/


int item;
if (isFull()==0){ //not full
printf("\nEnter an element to be pushed:");
scanf("%d", &item);
stack[++top] = item;
}
Display();
}
int Pop() { /*POP FUNCTION*/
int ret;
if (isEmpty()==0) //if not empty
{
ret = stack[top--];
printf("\nPopped element is:- %d", ret);
}
return ret;
}

void Palindrome() { /*PALINDROME FUNCTION*/


int i, temp = top+1, count=0;
for(i=0; i<temp/2; i++){
if(stack[i] == stack[top-i]){
count++;
}
if((temp/2)==count)
printf("\nStack is a Palindrome numbers ");
else
printf("\nStack is not a palindrome!!");
}
void Display() {int i;
if (isEmpty()==0){
printf("\nThe stack contents are:");
for(i=top; i>=0; i--)
printf("\t %d", stack[i]);
}
}
void main() {
int ch,item;
do{
printf("\n MAIN MENU:");
printf("1.PUSH\n 2.POP \n3.PALINDROME check \n 4.DISPLAYstatus 5. Exit");
printf("\nEnter Your Choice: ");
scanf("%d", &ch);
switch(ch){
case 1: Push(item); break;
case 2: Pop(); break;
case 3: Palindrome(); break;
case 4: Display(); break;
case 5: exit(0); break;
}
}while (1);
}

Dept. of ISE,SIT, Mangaluru Page|7


Data Structures Laboratory - 18CSL38 III Semester / B.E
OUTPUT
MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit
Enter Your Choice: 2
Stack is Underflow!

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 1

Enter an element to be pushed: 12


The stack contents are: 12

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 1

Enter an element to be pushed: 34


The stack contents are: 34 12

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 1

Enter an element to be pushed: 45


The stack contents are: 45 34 12

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 1

Enter an element to be pushed: 34


The stack contents are: 34 45 34 12

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 1
Enter a element to be pushed: 12
The stack contents are: 12 34 45 34 12

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 1
Enter an element to be pushed: 23
Stack is Overflow!
The stack contents are: 12 34 45 34 12

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice: 3

Popped element is:- 12


Popped element is:- 34
Stack contents are Palindrome

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter your choice: 4
The stack contents are: 12 34 45

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter your choice: 3
Popped element is:- 45
Stack contents are not palindrome!!

MAIN MENU: 1.PUSH 2.POP 3.PALINDROME check 4.DISPLAY status 5. Exit


Enter Your Choice:5

Dept. of ISE,SIT, Mangaluru Page|8


Data Structures Laboratory - 18CSL38 III Semester / B.E

EXPERIMENT – 04: Infix Expression to Postfix

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 .

Steps :
• Read the infix expression as a string.
• Scan the expression character by character till the end. Repeat
the following operations:-
• If it is an operand add it to the postfix expression.
• If it is a left parenthesis push it onto the stack.
• If it is a right parentheses, pop out elements from the stack
and add it to the postfix string. Pop out the left parentheses
but don’t add to postfix. (Observe the return value of “(“ of
stack and “)” of Input)
• If it is an operator, compare its precedence with that of the
element at the top of stack.
o If it is greater push it onto the stack.
o Otherwise pop and add elements to the postfix expression
until base symbol #.
o If # is reached, i.e the end of the expression, pop out
any leftover elements in the stack till it becomes empty.
o Append a null terminator at the end display the result

Code:
#include<stdio.h>
#include<string.h>
int Stack (char symbol) {
switch(symbol){
case '+': return 2;
case '-': return 2;
case '*': return 4;
case '/': return 4;
case '%': return 4; //modulus ex- 5% 3=2
case '^': return 5; //power
case '(': return 0;
case '#': return -1;
default : return 8;
}
}

Dept. of ISE,SIT, Mangaluru Page|9


Data Structures Laboratory - 18CSL38 III Semester / B.E
int Input (char symbol) {
switch(symbol) {
case '+': return 1;
case '-': return 1;
case '*': return 3;
case '/': return 3;
case '%': return 3; //mod
case '^': return 6; //power
case '(': return 9;
case ')': return 0;
default : return 7;
}
}
void Infix_postfix(char infix[], char postfix[]){
int top = -1,j = 0, i;
char s[30], symbol;
s[++top] = '#';
for(i=0; i < strlen(infix); i++) {
symbol = infix[i];
if(Input (symbol)==7 ) {
postfix[j++] =symbol;
continue;
}
while(Stack (s[top]) > Input (symbol)){
postfix[j++] = s[top--];
}
if( Stack (s[top]) != Input (symbol))
s[++top] = symbol;
else
top--;
}
while(s[top] != '#')
postfix[j++] = s[top--];
postfix[j] = '\0';
printf("\nThe infix expression is:%s \nThe postfix expression is:%s ",infix, postfix);
}
void main(){
char infix[20], postfix[20];
printf("\nEnter the infix expression :");
gets(infix);
Infix_postfix(infix,postfix);
} Obtain the postfix expression for the following and observe the output :

1) ((A+B)*C-(D-E))%(F+G) Expected Answer: AB+C*DE--FG+%


2) A/B^C+D*E-A*C Expected Answer: ABC^/DE*+AC*-

Few examples:
(1+2+3)➔ left to right execution 3+3➔ 6
(1*2-3)➔ left to right, * has higher priority so 3-3=0
(1%3%6)➔ left to right 1%3➔1 1%6➔ 1
(2^3^2) right to left 2^9 ➔512

Dept. of ISE,SIT, Mangaluru Page|10


Data Structures Laboratory - BCSL305 III Semester / B.E
EXPERIMENT – 05.A: Evaluation of Suffix expression
Design, Develop and Implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^

Step 1: Read the infix expression as a string.


Step 2: Scan the expression character by character till the end. Repeat
the following operations
a. If it is an operand push it onto the stack.
b. If it is an operator
Pop out two operands from stack.
Apply the operator onto the popped operands.
Store the result back on to the stack.
Step 3: On reaching the end of expression, pop out the contents of the
stack and display as the result.
CODE:
# include<stdio.h>
#include<math.h>
#include<string.h>
#include <ctype.h>
int Compute(char symbol, int op1, int op2){
int Temp=1,i;
switch(symbol){
case'+' :Temp=op1 + op2; break;
case'-' :Temp=op1 -op2;break;
case'*' :Temp=op1 * op2;break;
case'/' :if (op2 != 0) Temp= op1 / op2;break;
case'%' :if (op2 != 0) Temp=op1% op2; break;
case'^' :for(i=1;i<=op2;i++)
Temp=Temp*op1;
break;
default: break;
}
return (Temp);
}
int main(){
int s[20], op1, op2,top=-1, i;
char postfix[20], symbol;
printf("\nEnterthe postfix expression:");
scanf("%s",postfix);
for(i=0; i<strlen(postfix); i++){
symbol = postfix[i];
if(isdigit(symbol))
s[++top] = symbol -'0';
else{
op2 = s[top--];
op1 = s[top];
s[top]= Compute(symbol, op1, op2);
}
}
printf("\n The result is : %d\n", s[top]);
}
OUTPUT: cc Lab5a.c –lm { Sample Expression: 935*64-/+ ,Result=16
Dept. of ISE, SIT, Mangaluru Page|11
Data Structures Laboratory - BCSL305 III Semester / B.E
EXPERIMENT – 05.B: Tower of Hanoi

Design, Developand Implement a Program in C for the following Stack Applications


a) Evaluation of Suffixexpression with single digit operands and operators: +, -, *, /, %, ^
b) Solving Tower of Hanoi problem with n disks._ _

Algorithm:
Step 1: Move a tower of height-1 to an intermediate pole, using the
final pole.
Step 2: Move the remaining disk to the final pole.
Step 3: Move the tower of height-1 from the intermediate pole to the

CODE:
#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("\n Move 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: ");
scanf("%d", &n);
Tower(n, 'S', 'T', 'D');
printf("\n\n Total Number of moves are: %d", (int)pow(2,n)-1);
}

OUTPUT
cc Lab5b.c –lm

Enter the number of discs: 3

Move disc 1 from S to D


Move disc 2 from S to T
Move disc 1 from D to T
Move disc 3 from S to D
Move disc 1 from T to S
Move disc 2 from T to D
Move disc 1 from S to D

Total Number of moves are: 7

1 S D
2 S T
1 D T
3 S D
1 T S
2 T D
1 S D

Dept. of ISE, SIT, Mangaluru Page|12


Data Structures Laboratory - BCSL305 III Semester / B.E
EXPERIMENT – 06: Circular QUEUE OPERATIONS
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

Steps:
1. Insertion
• Display overflow if rear >-1 and front is rear+1
• Otherwise Insert new element at updated rear (i.e rear+1)
2. Deletion
• Display Underflow if front=0 and rear=-1
• Otherwise return the element at front and update front
(i.e front=front +1 if no element found( if rear=front)
then resetfront and rear.
3. Display
• Display all element from front to rear in circular fashion

CODE:
#include<stdio.h>
#include<stdlib.h>
char q[10];
int max=4;
int front=-1,rear=-1;
int isFull(){
if((front+1)%max==(rear+1)% max && rear>-1)
{
return 1; //if full
}
else
return 0; //if not full
}
int isEmpty(){
if((front==-1)&&(rear==-1)) {
return 1; //if empty
}
else{
return 0; //if not empty
}
}

Dept. of ISE, SIT, Mangaluru Page|13


Data Structures Laboratory - BCSL305 III Semester / B.E
void Insert(){
if(isFull()==0) { //if not full
printf("Enter element to insert:");
rear=(++rear)%max;
scanf(" %c",&q[rear]); //read a char and insert if cir.queue is not full
printf("front=%d Rear=%d", front,rear);
}
else
printf("Queue is overflow\n");
}
void Delete(){
if(isEmpty()==0){ //if not empty
front=(++front)%max;
printf("Deleted element is:%c\n", q[front]); //remove and delete a char from queue
printf("front=%d Rear=%d", front,rear);
if(front==rear)
{
printf("true");
front=rear=-1;
}
}
else
printf("Queue is NOW empty\n");
}
void Display(){
int i=(front+1) %max;
if(isEmpty()==0){
do{
printf("\t%c",q[i]);
i=(i+1)%max;
} while(i!=(rear+1)%max);
}
else
printf("Queue is empty\n");
}
int main()
{
int ch;
do {
printf("\n Circular Queue operations\n 1.Insert\n 2.Delete\n 3.Display\n 4.Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: exit(0);
}
}while(1);
}
Dept. of ISE, SIT, Mangaluru Page|14
Data Structures Laboratory - BCSL305 III Semester / B.E

Observe the output and draw circular queue status


(diagram) for the following sequence of operations.

Insert → a, Insert → b, Insert → c,


Insert → d,
Insert → e, Display Delete Insert → e
,
Delete Delete Delete Delete Delete

EXPERIMENT – 07: Singly Linked List Operations


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, 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>
int MAX=4,count=0;
struct student{
char usn[10], name[30], branch[5];
char phno[10];
int sem;
struct student *next;
};
typedef struct student NODE;
NODE *head,*newnode;
NODE* Getnode(){
newnode=(NODE*)malloc(sizeof(NODE));
printf("\nEnter USN, Name, Branch, Sem, Ph.No:");
scanf("%s%s%s%d%s",
newnode->usn,newnode->name,newnode->branch, &newnode->sem, newnode->phno);
newnode->next=NULL;
count++;
return (newnode);
}

void Display(NODE *p){


if( p!= NULL){
printf("\n----STUDENT DATA ---- \n USN\t\tNAME\t\tBRANCH\tSEM\tPh.NO.");
while(p!=NULL){
printf("\n%s\t%s\t\t%s\t%d\t%s", p->usn, p->name, p->branch, p->sem, p->phno);
p = p->next;
}
printf("\nNumber of nodes%d",count);
}
else
printf("\nNo data available!!\n");
}

Dept. of ISE, SIT, Mangaluru Page|15


Data Structures Laboratory - BCSL305 III Semester / B.E

NODE *Insert_Front(NODE *head){


NODE *newnode,*p;
if(count==MAX)
printf("\n Overflow!!");
else {
newnode=Getnode();
if(head==NULL)
head= newnode;
else{
newnode->next=head;
head=newnode;
}
}
return (head);
}
NODE* Insert_Rear(NODE *head){
NODE *newnode,*p;
if(count==MAX)
printf("\n Overflow!!");
else {
newnode=Getnode();
if(head==NULL)
head=newnode;
else{
p=head;
while(p->next!=NULL){
p=p->next;
}
p->next=newnode;
}
}
return (head);
}
NODE* Delete_Front(NODE *head){
NODE *p;
p=head;
if(head==NULL)
printf("\nEmpty(Underflow)");
else {
head=head->next;
free(p);
count--;
}
return head;
}
NODE* Delete_Rear(NODE *head){
NODE *p, *q;
p=head;
if(head==NULL)
printf("\nEmpty(Underflow)");
else {
if (head->next==NULL)
head=NULL;
else {
while(p->next!=NULL){
q=p;
Dept. of ISE, SIT, Mangaluru Page|16
Data Structures Laboratory - BCSL305 III Semester / B.E
p=p->next;
}
q- >next=NULL;
free(p);
count--;
}
}
return head;
}
int main(){
int ch, i, n;
NODE *head=NULL;
printf("\n----------Student Database--------- ");
printf("\nHow many student data you want to create: ");
scanf("%d", &n);
for(i=0;i<n;i++)
head=Insert_Front(head); //Creation
do {
printf("\nMENU:\n1.Display\n2.Insert-Front \n3.Delete Front\n4.Insert-Rear \n5.Delete Rear");
printf("\n 6.Stack-PUSH\n 7.Stack-POP\n 8.Exit \nEnter your choice: ");
scanf("%d", &ch);
switch(ch) {
case 1: Display(head); break;
case 2: head=Insert_Front(head); break;
case 3: head=Delete_Front(head); break;
case 4: head=Insert_Rear(head); break;
case 5: head=Delete_Rear(head); break;
case 6: head=Insert_Rear(head); break; //stack-Push
case 7: head=Delete_Rear(head); break; //stack-Pop
case 8: exit(0);
}
}while(1);
}

Dept. of ISE, SIT, Mangaluru Page|17


Data Structures Laboratory - BCSL305 III Semester / B.E

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<stdio.h>
#include<stdio.h>
#include<stdlib.h>
int MAX=4,count=0;
struct emp{
char ssn[5],name[20], dept[10], phno[10],desig[15];
int sal;
struct emp *left, *right;
};
typedef struct emp NODE;
NODE* Getnode(){
NODE *node=(NODE*)calloc(1,sizeof(NODE));
printf("\nEnter SSN, Name, Dept, Designation, Sal, Ph.No:");
scanf("%s%s%s%s%s%d",node ->ssn, node ->name, node ->dept, node ->phno ,node ->desig,&node -
>sal);
node->right=node ->left =NULL;
count ++;
return node;
}
void Display(NODE *p){
if(p != NULL){
printf("\nSSN\tNAME\tDEPT\tDESINGATION\tSAL\tPh.NO.\n");
while(p!=NULL){
// printf("count:%d %u",count,p);
printf("\n%s\t%s\t%s\t%s\t%s\t\t%d",p->ssn, p->name, p->dept, p->phno,p->desig,p->sal);
p = p->right;
}
printf("\nNumber of nodes%d",count);
}
else
printf("\nNo data available!!\n");
}
NODE* Insert_Rear(NODE *head){
NODE *p=head, *newnode;
if(count==MAX)
printf("\n Overflow!!");
else{
newnode=Getnode();
if(head==NULL)
head=newnode;
else{
while(p->right!=NULL){
p=p->right;
}

Dept. of ISE, SIT, Mangaluru Page|18


Data Structures Laboratory - BCSL305 III Semester / B.E
p- >right=newnode;
newnode->left=p;
}
}
return head;
}
NODE* Insert_Front(NODE *head){
NODE *p=head, *newnode;
if(count==MAX)
printf("\n Overflow!!");
else {
newnode=Getnode();
if(head==NULL)
head=newnode;
else{
newnode->right=head;
head->left=newnode;
head=newnode;
}
}
return head;
}
NODE* Delete_Rear(NODE *head){
NODE *p=head,*q;
if(head==NULL)
printf("\nList is Empty (QUEUE)");
else {
while(p->right!=NULL)
p=p->right;
if( p->left !=NULL){
q=p->left;
q- >right=NULL;
}
else
head=NULL;
free(p);
count--;
}
return head;
}
NODE* Delete_Front(NODE *head){
NODE *p=head,*q;
if(head==NULL)
printf("\nList is Empty (QUEUE)");
else {
if( p->right ==NULL)
head=NULL;
else{
head=p->right;
head->left=NULL;
}
free(p);
count--;
Dept. of ISE, SIT, Mangaluru Page|19
Data Structures Laboratory - BCSL305 III Semester / B.E
}
return head;
}
int main(){
int ch, i, n;
NODE *head=NULL;
printf("\nHow many employees data you want to create: ");
scanf("%d", &n);
for(i=0;i<n;i++)
head=Insert_Rear(head);
do{
printf("\n1.Display\n2.Insert-Front\n3.Insert-Rear\n4.Deletion-Front");
printf("\n5.Deletion-Rear\n6.Queue-Insertion\n7.Queue-Deletion \n8.Exit\n");
printf( "Enter your choice: ");
scanf("%d", &ch);
switch(ch) {
case 1 : Display (head); break;
case 2 : head=Insert_Front (head); break;
case 3 : head=Insert_Rear (head); break;
case 4 : head=Delete_Front (head); break;
case 5 : head=Delete_Rear(head); break;
case 6 : head=Insert_Rear (head); break; //queue insertion
case 7 : head=Delete_Front(head); break; //queue deletion
case 8 : exit(0); break;
}
}while(1);
}
Doubly Linked list

Dept. of ISE, SIT, Mangaluru Page|20


Data Structures Laboratory - BCSL305 III Semester / B.E

EXPERIMENT – 09: Singly Circular Linked List (SCLL)


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.

Algorithm:
Step for Node creation
➢ Get a node and assign coefficient and power of x,y,z
➢ Attach this to head in circular linked list fashion
Step for Node display
➢ From the first node last node display all data fields of
a node in a standard form Coeff.X^powx.Y^powx.Z^powxGet a
node and assign coefficient and power of x,y,z
Steps for compare
➢ Return aif corresponding coefficient X,Y and Z of two
polynomials are same, otherwise return 0.

Steps for Evaluate


➢ For all the terms evaluate and return the final answer.

Steps for Adding two polynomils


➢ Repeat for all terms of both olynomials
➢ Compare a terms of first polynomial with a term of second
polynomial
➢ If powers of X,Y and Z are same then add corresponding
coefficients and mark both terms and the resultant terms
to Result polynomial( to avoid further consideration)
➢ Otherwise consider the other term of second polynomial if
no matching powers of X,Y and Z found add the first
polynomial term to resultant and mark it Repeat this for
all terms of first polynomial
➢ If any unmarked terms found in second then add it to the

Dept. of ISE, SIT, Mangaluru Page|21


Data Structures Laboratory - BCSL305 III Semester / B.E
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct node{
int coef, ex, ey, ez,flag;
struct node *link;
};
typedef struct node NODE;
NODE* Insert(int coef,int x,int y,int z, NODE *head){
NODE *newnode=(NODE*) calloc(1,sizeof(NODE)), *temp=head;
newnode->coef=coef;
newnode->ex=x;
newnode->ey=y;
newnode->ez=z;
newnode->flag=0;
if(head==NULL)
head=newnode;//if no node then newly created node is first node
else{
while(temp->link!=head){
temp=temp->link;
}
temp->link=newnode; //change rear
}
newnode->link=head; //form as circular header -by connecting to head node
return head;
}
NODE *Read_poly(NODE *head){
int ex, ey, ez, coef, n,i;
printf("\nEnter number of terms in polynomial terms:");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\n Enter coeff and powers of x,y ,z: ");
scanf("%d%d%d%d", &coef,&ex, &ey, &ez);
head=Insert(coef,ex,ey,ez,head);
}
return head;
}
void Display(NODE *head){
NODE *temp=head->link; //to point to the first data node
while(temp!=head){
printf("%+dX^%dY^%dZ^%d", temp->coef, temp->ex, temp->ey, temp->ez);
temp=temp->link;
}
}
void Evaluate( int x, int y, int z,NODE *head){
NODE *temp=head->link;
int result=0;
while(temp!=head){
result = result + (temp->coef * pow(x,temp->ex) * pow(y,temp->ey) *pow(z,temp->ez));
temp=temp->link;
}
printf("\n Polynomial result is: %d", result);
}
Dept. of ISE, SIT, Mangaluru Page|22
Data Structures Laboratory - BCSL305 III Semester / B.E
NODE* Add_poly(NODE *h1,NODE *h2,NODE *h3){
NODE *p1=h1->link,*p2;
do{
p2=h2->link;
do{
if((p1->flag !=1 )&& (p2->flag !=1)&&(p1->ex==p2->ex)&& (p1->ey == p2->ey ) &&
(p1->ez == p2->ez)) {
h3=Insert(p1->coef+p2->coef,p1->ex,p1->ey,p1->ez,h3);
p1->flag=1;
p2->flag=1; //mark visited
}
p2=p2->link;
}while(p2!=h2);
p1=p1->link;
}while(p1!=h1);
p1=h1->link; //reset to copy all remaining terms
while(p1!=h1){
if(p1->flag !=1){//if not considered
h3=Insert(p1->coef,p1->ex,p1->ey,p1->ez,h3);
p1->flag=1;
}
p1=p1->link; //next term of A
}
p2=h2->link;
while(p2!=h2){
if(p2->flag!=1){//if not considered
h3=Insert(p2->coef,p2->ex,p2->ey,p2->ez,h3);
p2->flag=1;
}
p2=p2->link; //next term of A
}
return h3;
}
int main(){
NODE *h1=NULL,*h2=NULL,*h3=NULL;
int ch,x,y,z;
do{
printf("\n1.Create 2. Display 3. Add 4. Evaluate 5.Exit\n Enter your choice:");
scanf("%d", &ch);
switch(ch) {
case 1: h1=Insert(0,0,0,0,h1);//header node creation
h2=Insert(0,0,0,0,h2);
h3=Insert(0,0,0,0,h3);
printf("\nEnter polynomial to evaluate:\n");
h1=Read_poly(h1);
h2=Read_poly(h2);
break;
case 2: printf("\nPolynomial A is:");
Display(h1);
printf("\nPolynomial B is:");
Display(h2);
break;

Dept. of ISE, SIT, Mangaluru Page|23


Data Structures Laboratory - BCSL305 III Semester / B.E
case 3: h3=Add_poly(h1,h2,h3);
printf("\nPolynomial C is:");
Display(h3);
break;
case 4: printf("\n Enter value for x, y, z, terms to evaluate:");
scanf("%d%d%d", &x, &y, &z);
Evaluate(x,y,z,h1);
Evaluate(x,y,z,h2);
break;
case 5: exit(0);
}
} while(1);
return 0;
}
OUTPUT
cc Lab9.c –lm
1.Create 2. Display 3. Add two poly 4. Evaluate 5.Exit
Enter your choice:1
Enter polynomial to evaluate:
Enter number of terms in polynomial terms:2
Enter coeff and powers of x,y ,z: 3 1 1 2
Enter coeff and powers of x,y ,z: 6 1 2 1
Enter number of terms in polynomial terms:2
Enter coeff and powers of x,y ,z: 9 2 1 1
Enter coeff and powers of x,y ,z: 10 1 2 1
1.Create 2. Display 3. Add two poly 4. Evaluate 5.Exit
Enter your choice:3
Polynomial C is:+16X^1Y^2Z^1+3X^1Y^1Z^2+9X^2Y^1Z^1
1.Create 2. Display 3. Add two poly 4. Evaluate 5.Exit
Enter your choice:2
Polynomial A is:+3X^1Y^1Z^2+6X^1Y^2Z^1
Polynomial B is:+9X^2Y^1Z^1+10X^1Y^2Z^1
1.Create 2. Display 3. Add two poly 4. Evaluate 5.Exit
Enter your choice:4
Enter value for x, y, z, terms to evaluate:1 1 1
Polynomial result is: 9
Polynomial result is: 19
1.Create 2. Display 3. Add two poly 4. Evaluate 5.Exit
Enter your choice:5

Dept. of ISE, SIT, Mangaluru Page|24


Data Structures Laboratory - BCSL305 III Semester / B.E
EXPERIMENT – 10: Binary Search Tree (BST)
1. Design, Develop and Implement a menu driven Program in C for the following operations on Binary
Search Tree (BST) of Integers
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
e. Exit

Steps:

1) Binary Search Tree-BST Creation


➢ If no node exist , then create a node , insert data
into data field, set left and right child to null
,return
➢ If head is not null, compare data field of the node
,traverse to left branch if data field of the node is
less than the new data to insert,
➢ Traverse to right branch of the node if data field is
greater than data to insert.
➢ Repeat above two step until a null node.
➢ If null node add the node by setting the address field
to last child node and return.
2) Binary Search Tree BST-Creation
➢ If no node exist , then display proper prompt
➢ Traverse to left branch if data field is greater than
data to search
➢ Traverse to right branch if data field is lesser than
data to search
If found or not found display proper message
3) Traverse
➢ If head node is not null, then recursively traverse
o If preorder: DATA → LEFT child → Right Child
o If postorder: LEFT child → Right Child→ DATA
o If Inorder: LEFT child → DATA →Right Child

CODE:
#include <stdio.h>
#include <stdlib.h>
struct BST {
int data;
struct BST *left, *right;
};
typedef struct BST NODE;
Dept. of ISE, SIT, Mangaluru Page|25
Data Structures Laboratory - BCSL305 III Semester / B.E
NODE* Createtree(NODE *node, int data){
if (node == NULL) {
NODE *temp= (NODE*)calloc(1,sizeof(NODE));
temp->data = data;
return temp; //create and insert new node to BST
}
if (data < node->data) //TRAVERSE LEFT of NODE if key is less than data
node->left = Createtree(node->left, data);
else if (data > node->data) //TRAVERSE LEFT of NODE if key is greater than data
node -> right = Createtree(node->right, data);
else //reject the duplicate
printf(“duplicate data found”);
return node;
}
NODE* Search(NODE *node, int data){
if(node == NULL) //insert at proper place
printf("\n Element not found");
else if(data < node->data) //TRAVERSE LEFT of NODE if key is less than data
node->left=Search(node->left, data);
else if(data > node->data) //TRAVERSE LEFT of NODE if key is greater than data
node->right=Search(node->right, data);
else{
printf("\n Element found: %d", node->data);
}
return node;
}
void Inorder(NODE *node){ //LEFT-ROOT-RIGHT
if(node != NULL){
Inorder(node->left);
printf("%d\t", node->data);
Inorder(node->right);
}
}
void Preorder(NODE *node){ //ROOT—LEFT-RIGHT
if(node != NULL) {
printf("%d\t", node->data);
Preorder(node->left);
Preorder(node->right);
}
}
void Postorder(NODE *node){ //LEFT –RIGHT-ROOT
if(node != NULL) {
Postorder(node->left);
Postorder(node->right);
printf("%d\t", node->data);
}
}
void main()
{
int no, ch, i, n;
NODE *root=NULL;
do{
printf("\n1.Creation\n2.Search\n3. Inorder \n4. Preorder \n5. Postorder \n6.Exit");

Dept. of ISE, SIT, Mangaluru Page|26


Data Structures Laboratory - BCSL305 III Semester / B.E
printf("\n Enter your choice: ");
scanf("%d", &ch);
switch (ch){
case 1: printf("\nEnter total numbers to be added to binary tree: " );
scanf("%d", &n);
printf("\nEnter the values for the BST");
for(i=0; i<n; i++){
scanf("%d", &no);
root=Createtree(root, no);
}
break;
case 2: printf("\nEnter the element to search: ");
scanf("%d", &no);
Search(root, no);
break;
case 3: : printf("\nInorder Traversal: \n");
Inorder(root);
break;
case 4 :printf("\nPreorder Traversal: \n");
Preorder(root);
break;
case 5: printf("\nPostorder Traversal: \n");
Postorder(root);
break;
case 6: exit(0);
default: printf("\n Wrong option");
break;
}
} while (1);
}
OUTPUT
1.Insertion 2.Search an Element 3.Delete an Element
4.Inorder 5.Preorder 6.Postorder 7.Exit
Create BST for the following data : 6,9,5,2,8,15,24,14,7,8,5,2
Perform following operations
1. Insertion 6,9,5,2,8,15,24,14,7,8,5,2
2. Search for 15 Deletion : 2 Inorder Preorder
3. Post order traverse
Represent your response in graphical form also

Observation: //sample data {6,9,5,2,8,15,24,14,7,8,5,2};

Dept. of ISE, SIT, Mangaluru Page|27


Data Structures Laboratory - BCSL305 III Semester / B.E

Dept. of ISE, SIT, Mangaluru Page|28


Data Structures Laboratory - BCSL305 III Semester / B.E
EXPERIMENT – 11: Operations on Graph(G)
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

Algorithm:
Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered
Step for BFS(G,v) (Breadth First Search)

➢ Mark vas discovered and add it to q at rear.

➢ Visit all vertices from front to rear only once and after visiting a vertices, mark it as
visited and also display the data containing in the vertices
Step for DFS(G,v) (Depth First Search)

➢ Mark vas discovered and push it to top of q at rear.


➢ Visit all vertices only once and after visiting a vertices, mark it as visited and also
display the data containing in the vertices.
CODE:
#include<stdlib.h>
#include<stdio.h>
int adj[20][20],visited[20], G[20], front = -1,rear =-1, top = -1,n,i;
void BFS(int v){ //uses G as Queue
int cur;
visited[v] = 1;
G[++rear] = v;
while(front!=rear){
cur = G[++front];
for(i=1;i<=n;i++){
if((adj[cur][i]==1)&&(visited[i]==0)){
G[++rear]=i;
visited[i]=1;
printf("%d→%d \n",cur,i);
}
}
}
}
void DFS(int v){ //uses G as Stack
visited[v]=1;
G[++top] = v;
for(i=1;i<=n; i++){
if(adj[v][i] == 1 && visited[i] == 0 ) {
printf("\n%d -- %d", v, i);
DFS(i);
}
}
}
int main(){
Dept. of ISE, SIT, Mangaluru Page|29
Data Structures Laboratory - BCSL305 III Semester / B.E
int ch, start, i, j;
printf("\nEnter the number of vertices in graph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d", &adj[i][j]);
do{
printf("\n1. Reachable vertices using BFS\n2. Reachable vertices using DFS");
printf("\n3. Exit");
printf("\n Enter your choice: ");
scanf("%d", &ch);
for(i=1;i<=n;i++)
visited[i] = 0;
printf("\n Enter the starting vertex: ");
scanf("%d", &start);
printf("\nNodes reachable from starting vertex %d are:", start);
switch(ch){
case 1: BFS(start); break;
case 2: DFS(start); break;
case 3: exit(0);
}
}while(ch!=3);
}
OUTPUT
BFS:
Enter the starting vertex: 1
Nodes reachable from starting vertex 1 are: 1->2 1->3 2->4
DFS
Nodes reachable from starting vertex 4 are: 4 -- 1 1 -- 2 2 -- 3

Draw a graph and apply BFS and DFS

Dept. of ISE, SIT, Mangaluru Page|30


Data Structures Laboratory - BCSL305 III Semester / B.E
EXPERIMENT – 12: Liner probing
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

Algorithm:

Read employee record, generate hash value using key


Scan the hash table for inserting the record in the proper place , if place is
empty , then insert the record otherwise the go the next location.
If a record found the table display a message and try for next unused
location.
If no place found , display a message “ Hash table is full”

CODE:
#include<stdio.h>
#include <stdlib.h>
#define MAX 10
struct employee{
int id;
char name[15];
};
typedef struct employee EMP;
EMP emp[MAX];
int a[MAX];
void Linear_prob(int key, int num){
int flag=0, i=key;
if(a[i] == -1)
flag=1;
else{
printf("\nCollision Detected...!!!\n");
i=(key+1)%MAX;
do{
if(a[i] == -1) {
flag = 1;
break;
}
else
i=(++i)%MAX;
}while(i!=key && flag==0);
}
Dept. of ISE, SIT, Mangaluru Page|31
Data Structures Laboratory - BCSL305 III Semester / B.E

if(flag==0)
printf("\n Hash table is full");
else{
printf("\nEnter emp id: ");
scanf("%d",&emp[i].id);
printf("\nEnter emp name: ");
scanf("%s",emp[i].name);
a[i]=i;
printf("\nCollision avoided successfully using LINEAR PROBING\n");
}
}
void Display(){
int i, ch;
printf("\n1.Display ALL\n2.Filtered Display \n Enter the choice:");
scanf("%d",&ch);
printf("\nHTKey\tEmpID\tEmpName");
for(i=0; i<MAX; i++){
if(ch==2 && a[i] == -1)
continue;
else
printf("\n%d\t%d\t%s", i, emp[i].id, emp[i].name);
}
}
int main(){
int num, key, i;
int ch = 1;
printf("\nCollision handling by linear probing: ");
for (i=0; i < MAX; i++) {
a[i] = -1;
}
do{
printf("\nEnter the data: ");
scanf("%d", &num);
Linear_prob(num % 100,num);
printf("\nDo you wish to continue? (1/0): ");
scanf("%d",&ch);
}while(ch);
Display();
}

OUTPUT
#Run 1
Collision handling by linear probing:
Enter the data: 2
Enter emp id: 100
Enter emp name: Ricky
Collision avoided successfully using LINEAR PROBING
Do you wish to continue? (1/0): 1
Enter the data: 7
Enter emp id: 101
Enter emp name: Reena
Collision avoided successfully using LINEAR PROBING
Do you wish to continue? (1/0): 0
1.Display ALL 2.Filtered Display
Dept. of ISE, SIT, Mangaluru Page|32
Data Structures Laboratory - BCSL305 III Semester / B.E
Enter the choice:1
HTKey EmpID EmpName
0 0
1 0
2 100 Ricky
3 0
4 0
5 0
6 0
7 101 Reena
8 0
9 0
#Run 2
Collision handling by linear probing:
Enter the data: 2
Enter emp id: 101
Enter emp name: Raj
Collision avoided successfully using LINEAR PROBING
Do you wish to continue? (1/0): 1
Enter the data: 4
Enter emp id: 102
Enter emp name: Raina
Collision avoided successfully using LINEAR PROBING
Do you wish to continue? (1/0): 0
1.Display ALL 2.Filtered Display
Enter the choice:2
The hash table is:
HTKey EmpID EmpName
2 101 Raj
4 102 Raina
#Run 3
Collision handling by linear probing:
Enter the data: 2
Enter emp id: 100
Enter emp name: Reema
Collision avoided successfully using LINEAR PROBING
Do you wish to continue? (1/0): 1
Enter the data: 2
Collision Detected...!!!
Enter emp id: 101
Enter emp name: Robert
Do you wish to continue? (1/0): 1
Enter the data: 2
Collision Detected...!!!
Enter emp id: 103
Enter emp name: Richard

Dept. of ISE, SIT, Mangaluru Page|33


Data Structures Laboratory - BCSL305 III Semester / B.E

Sample Viva Questions


1. What is an array?
2. What is the use of top in Stack?
3. How top is updated during stack operation?
4. How do you create an array to hold 15 integer items?
5. How many memory locations are utilized for 15 items integer array?
6. What is pointer?
7. What is the difference between &a and *a in C code?
8. What is the use of NULL?
9. How do you keep track of queue, during its operations?
10. What are the conditions to be checked during stack operation?
11. What is dynamic stack?
12. How dynamic stack is useful over static allocation?
13. When do you sayoverflow and underflow?
14. What is pattern?
15. What is the logic used in simple pattern matching algorithm?
16. Differentiate Postfix, Prefix and Infix expression
17. What is the postfix and prefix of expression : a+b/c*d$e
18. What is recursion?
19. How stack is used during recursion?
20. What is the difference between recursion and infinite loop?
21. What is linked list?
22. What is the advantage of linked list over array?
23. How do you allocate memory to hold data consisting name and ID?
24. What is the use of sizeof in malloc function?
25. How do you design stack using linked list?
26. How do you implement queue using linked list?
27. What is the disadvantage of linked list
28. What is the idea of single linked list?
29. How Double linked list is different over single linked list?
30. What is the application of stack?
31. Give one application for queue?
32. When a SLL and DLL can be used?
33. How circular list differ over SLL?
34. Give the C structure for SLL. Assume Only one field of type int
35. Give the C structure for DLL. Assume Only one field of type int
36. What is traversing?
37. What are the operations that can be performed over SLL or DLL or CLL?
38. What is Head node?
39. What is the use of Head?
40. Evaluate the expression: AB+CDE -*/ given A=5, B=6 C=4 D=3 E=7
41. Give the piece of code to insert a node at end of the list assume necessary information?
42. How do you insert a node at the beginning of linked list?
43. How do you remove a node which is at the rear end?
44. Give the piece of code remove a node from the beginning.
45. What is the result of statement Head=NULL, if it contains 5 nodes.
46. Give the piece of code to add 5 nodes to a circular linked list.
47. What is a tree?
48. What is binary tree?
49. What is the use of binary tree?

Dept. of ISE, SIT, Mangaluru Page|34


50. How do you construct a binary tree?

51. Give the structure for implementing a Binary search tree.


52. What is skewed tree?
53. What is sibling?
54. For tree (assume a tree), give the preorder, postorder and inorder traversal.
55. What is expression tree?
56. How do you construct expression tree?
57. How do you construct BST for given inorder and postorder expression?
58. What is a graph?
59. How graph is useful in computer science?
60. How do create a graph?
61. What is adjacency matrix?
62. Assume a graph and give the adjacency matrix
63. What is the difference between BST and DFS?
64. What is hash key?
65. What is collision?
66. How do you handle collision?
67. How linear probing works?
68. For the given SLL, node NewNode and a SLL head is Root. What is effect of statements:
NewNode=Root; and Root =NewNode;
69. For the given SLL, node NewNode and a SLL head is Root. What is effect of statements:
NewNode→next=Root and Root→next =NewNode
70. For the given SLL, node NewNode and a SLL head is Root. What is effect of statements:
free(NewNode); and free(Root);
71. Give a piece of code to insert an element into the middle of array.
72. Give a piece of code to remove an element into the middle of array.
73. Give any one example for hash function.
74. What is the use of –lm option when you compile certain c program?
75. Give the piece of code to display content of SLL.
76. Give the piece of code to read data for node of DLL.
77. How do you retrieve content of integer array whose size is 10?
78. Identify the mistake in the below given piece of code
While(temp->next !NULL);
Temp->next=Temp ;
79. What is the effect of code : temp->next =temp and Temp=Temp->next
80. What is the use of (NODE) in malloc function ?
81. What is the effect of statement print(“%d”, a[0]) and print(“%d”, *a);
82. For the statement printf(“%d”, a[0]) , what is nature of array?
83. Create a structure a single linked list
84. Identify the mistake in the below given piece of code
if(Count=MAX);
Count++ ;
85. What is spanning tree?
86. What is data structure?
87. What is the application of Data structure?
88. What are the types of data structure? Give an example also
89. How do you represent polynomial using array of structure?
90. Give the structure of a polynomial with 3 variables (6XYZ)
Srinivas Institute of Technology
Department of Information Science and Engineering
Program Outcomes ( POs)
1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem Analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences.
3. Design/Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions for complex problems.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
11. Project Management and Finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and lifelong learning in the broadest context of technological
change.
Program Specific Outcomes (PSOs)
PSO1:Programming and software development skills: Ability to employ modern computer
languages, computing environments and standard practices for analysing, designing and
developing optimal solutions to deliver quality software products.
PSO2: Domain specific skills: Ability to apply techniques to develop computer based solutions
in various domains like Artificial Intelligence, Machine Learning, Network Engineering, Image
Processing, Web Technologies and Data Sciences.

You might also like