0% found this document useful (0 votes)
390 views78 pages

DS Lab Manual Updated

The document describes the laboratory manual for the Data Structures Laboratory course offered in the third semester of the Bachelor of Engineering program in Computer Science and Engineering. It includes the course code, credits, faculty in-charges, syllabus, list of programs to be developed involving concepts like arrays, strings, stacks, queues, linked lists, trees and graphs. The programs are aimed at providing practical experience in dynamic memory management and implementing operations on various linear and non-linear data structures.

Uploaded by

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

DS Lab Manual Updated

The document describes the laboratory manual for the Data Structures Laboratory course offered in the third semester of the Bachelor of Engineering program in Computer Science and Engineering. It includes the course code, credits, faculty in-charges, syllabus, list of programs to be developed involving concepts like arrays, strings, stacks, queues, linked lists, trees and graphs. The programs are aimed at providing practical experience in dynamic memory management and implementing operations on various linear and non-linear data structures.

Uploaded by

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

DATA STRUCTURES LABORATORY (BCSL305)

THE OXFORD COLLEGE OF ENGINEERING


Hosur Road, Bommanahalli, Bengaluru-560 068
2023-2024

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


LABORATORY MANUAL

SUBJECT NAME & CODE : DATA STRUCTURES LABORATORY (BCSL305)

SCHEME-B.E (CSE) : 2022 Scheme-VTU

SEMESTER : B.E, CSE-III SEM

FACULTY INCHARGES : Prof. Jesy Janet,

Prof. Asha Kumari,

Prof. Angel Donny.

DEPT OF CSE,TOCE,2023-24 Page 1


DATA STRUCTURES LABORATORY (BCSL305)

TABLE OF CONTENTS

SI.NO TITLE PAGE


NO.
1. Syllabus 4
2. CO-PO, PSO Mapping 7
3. 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 8-12
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.

4. 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
12-15
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.
5. 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
16-19
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
6. Design, Develop and Implement a Program in C for converting an Infi x Expression to
Postfix Expression. Program should support for both parenthesized and free
20-23
parenthesized expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and
alphanumeric operands.
7. Design, Develop and Implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, 24-28
%, ^ b. Solving Tower of Hanoi problem with n disks
8. Design, Develop and Implement a menu driven Program in C for the following 29-33
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

DEPT OF CSE,TOCE,2023-24 Page 2


DATA STRUCTURES LABORATORY (BCSL305)

with appropriate functions for each of the above operations


9. 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.
34-39
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
10. 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
40-47
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
11. Design, Develop and Imp lement 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) = 6x 2y2z-4yz 5+3x 3yz+2xy 5z-2xyz 3 b. Find the sum of two 48-54
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
12. Design, Develop and Implement a menu driven Program in C for the follow ing
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 55-60
c. Search the BST for a given element (KEY) and report the appropriate message d.
Exit

13. 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 61-64
the nodes reachable from a given starting node in a digraph using DFS/BFS method
14. 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 65-70
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.
15. VIVA Questions
71-77

DEPT OF CSE,TOCE,2023-24 Page 3


DATA STRUCTURES LABORATORY (BCSL305)

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

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

4. Design, Develop and Implement a Program in C for converting an Infi x Expression to Postfix
Expression. Program should support for both parenthesized and free parenthesized expressions with
the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands.

DEPT OF CSE,TOCE,2023-24 Page 4


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

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

7. Design, Develop and Implement a menu driven Program in C for the following operations on
Singly Linked List (SLL) of Student Data with the fields: USN, Name, Branch, Sem, PhNo a.
Create a SLL of N Students Data by using front insertion . b. Display the status of SLL and count
the number of nodes in it c. Perform Insertion / Deletion at End of SLL d. Perform Insertion /
Deletion at Front of SLL(Demonstration of stack) e. Exit

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

9. Design, Develop and Imp lement 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) = 6x 2y2z-
4yz 5+3x 3yz+2xy 5z-2xyz 3 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. Design, Develop and Implement a menu driven Program in C for the follow ing 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. Design, Develop and Implement a Program in C for the following operations on Graph(G) of
Cities a. Create a Graph of N cities using Adjacency Matrix. b. Print all the nodes reachable from a
given starting node in a digraph using DFS/BFS method
DEPT OF CSE,TOCE,2023-24 Page 5
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.

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

DEPT OF CSE,TOCE,2023-24 Page 6


DATA STRUCTURES LABORATORY (BCSL305)

(DATA STRUCTURES LABORATORY /BCSL305)

COURSE OUTCOMES:
On Completion of the course the students will be:

 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

CO-PO-PSO Mapping

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2

C205.1 3 1 - - - - - - - - - 1 1 -

C205.2 2 1 - - - - - - - - - 1 1 -

C205.3 3 1 - - - - - - - - - 1 1 -

C205.4 2 1 - - - - - - - - - 1 1 -

TARGET 2.5 1.0 - - - - - - - - - 1.0 1.0 -

DEPT OF CSE,TOCE,2023-24 Page 7


DATA STRUCTURES LABORATORY (BCSL305)

Program 1:

1.a. C program that declares a calendar as an array of 7 elements, where each element is a
structure with dynamically allocated strings for the day name and activity description

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

// Define the structure for a calendar day


struct CalendarDay {
char* dayName;
int date;
char* activity;
};

int main() {
// Declare an array of 7 CalendarDay structures
struct CalendarDay calendar[7];

// Initialize the calendar elements


for (int i = 0; i < 7; i++) {
calendar[i].dayName = (char*)malloc(20); // Allocate memory for day name
calendar[i].activity = (char*)malloc(100); // Allocate memory for activity description

// You can modify these lines to set specific values for each day
sprintf(calendar[i].dayName, "Day %d", i + 1);
calendar[i].date = i + 1;
sprintf(calendar[i].activity, "Activity for Day %d", i + 1);
}

// Print the calendar


for (int i = 0; i < 7; i++) {
printf("Day Name: %s\n", calendar[i].dayName);
printf("Date: %d\n", calendar[i].date);
printf("Activity: %s\n\n", calendar[i].activity);
}

// Free allocated memory


for (int i = 0; i < 7; i++) {
free(calendar[i].dayName);
free(calendar[i].activity);
}

DEPT OF CSE,TOCE,2023-24 Page 8


DATA STRUCTURES LABORATORY (BCSL305)

return 0;
}

OUTPUT:

Day Name: Day 1


Date: 1
Activity: Activity for Day 1

Day Name: Day 2


Date: 2
Activity: Activity for Day 2

Day Name: Day 3


Date: 3
Activity: Activity for Day 3

Day Name: Day 4


Date: 4
Activity: Activity for Day 4

Day Name: Day 5


Date: 5
Activity: Activity for Day 5

Day Name: Day 6


Date: 6
Activity: Activity for Day 6

Day Name: Day 7


Date: 7
Activity: Activity for Day 7

In this program:
1. We define a CalendarDay structure with three fields: dayName, date, and activity.
2. We declare an array of 7 CalendarDay structures to represent the 7 days of the week.
3. Inside a loop, we dynamically allocate memory for the dayName and activity fields using
malloc.
4. We initialize the elements of the calendar with some example data.
5. We print the contents of the calendar.
6. Finally, we free the dynamically allocated memory to avoid memory leaks.

DEPT OF CSE,TOCE,2023-24 Page 9


DATA STRUCTURES LABORATORY (BCSL305)

1b. 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>
#include <string.h>

// Define the structure for a calendar day


struct CalendarDay {
char* dayName;
int date;
char* activity;
};

// Function to create the calendar


void create(struct CalendarDay calendar[7]) {
for (int i = 0; i < 7; i++) {
calendar[i].dayName = (char*)malloc(20); // Allocate memory for day name
calendar[i].activity = (char*)malloc(100); // Allocate memory for activity description
}
}

// Function to read data from the keyboard


void read(struct CalendarDay calendar[7]) {
for (int i = 0; i < 7; i++) {
printf("Enter day name for Day %d: ", i + 1);
scanf("%s", calendar[i].dayName);

printf("Enter date for Day %d: ", i + 1);


scanf("%d", &calendar[i].date);

printf("Enter activity for Day %d: ", i + 1);


scanf(" %[^\n]", calendar[i].activity); // Read the whole line
}
}

// Function to display the calendar


void display(struct CalendarDay calendar[7]) {
printf("\nActivity Details for the Week:\n");
for (int i = 0; i < 7; i++) {
printf("Day Name: %s\n", calendar[i].dayName);
printf("Date: %d\n", calendar[i].date);
printf("Activity: %s\n\n", calendar[i].activity);

DEPT OF CSE,TOCE,2023-24 Page 10


DATA STRUCTURES LABORATORY (BCSL305)

}
}

int main() {
struct CalendarDay calendar[7];

create(calendar);
read(calendar);
display(calendar);

// Free allocated memory


for (int i = 0; i < 7; i++) {
free(calendar[i].dayName);
free(calendar[i].activity);
}

return 0;
}

OUTPUT:
Enter day name for Day 1: Monday
Enter date for Day 1: 06/11/2023
Enter activity for Day 1: Reading
Enter day name for Day 2: Tuesday
Enter date for Day 2: 07/11/2023
Enter activity for Day 2: Writing
Enter day name for Day 3: Wednesday
Enter date for Day 3: 08/11/2023
Enter activity for Day 3: Art & Craft
Enter day name for Day 4: Thursday
Enter date for Day 4: 09/11/2023
Enter activity for Day 4: Music
Enter day name for Day 5: Friday
Enter date for Day 5: 10/11/2023
Enter activity for Day 5: Dance
Enter day name for Day 6: Saturday
Enter date for Day 6: 11/11/2023
Enter activity for Day 6: Cycling
Enter day name for Day 7: Sunday
Enter date for Day 7: 12/11/2023
Enter activity for Day 7: Yoga
Activity Details for the Week:
Day Name: Monday

DEPT OF CSE,TOCE,2023-24 Page 11


DATA STRUCTURES LABORATORY (BCSL305)

Date: 06/11/2023
Activity: Reading

Day Name: Tuesday


Date: 07/11/2023
Activity: Writing

Day Name: Wednesday


Date: 08/11/2023
Activity: Art & Craft

Day Name: Thursday


Date: 09/11/2023
Activity: Music

Day Name: Friday


Date: 10/11/2023
Activity: Dance

Day Name: Saturday


Date: 11/11/2023
Activity: Cycling

Day Name: Sunday


Date: 12/11/2023
Activity: Yoga

 The create function allocates memory for the dayName and activity fields for each day of
the week.
 The read function reads day names, dates, and activity descriptions for each day from the
keyboard.
 The display function displays the activity details for the week.

DEPT OF CSE,TOCE,2023-24 Page 12


DATA STRUCTURES LABORATORY (BCSL305)

Program2:
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
withREP 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-
infunctions.
Theory:
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null
C language supports a wide range of built-in functions that manipulate null-terminated strings as
follows:

strcpy(s1, s2): Copies string s2 into string s1.


strcat(s1, s2): Concatenates string s2 onto the end of string s1.
strlen(s1): Returns the length of string s1.
strcmp(s1, s2): Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch): Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2): Returns a pointer to the first occurrence of string s2 in string s1

Algorithm:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: Search / find the pattern string PAT in the main string STR.
Step 4: if PAT is found then replace all occurrences of PAT in main string STR with REP string.
Step 5: if PAT is not found give a suitable error message.
Step 6: Stop.

#include <stdio.h>
#include <string.h>
// Function to perform pattern matching and replacement
void findAndReplace(char *mainString, const char *pattern, const char *replace) {
int mainLen = strlen(mainString);
int patternLen = strlen(pattern);
int replaceLen = strlen(replace);

if (patternLen == 0) {
DEPT OF CSE,TOCE,2023-24 Page 13
DATA STRUCTURES LABORATORY (BCSL305)

printf("Error: Pattern cannot be empty.\n");


return;
}
// Loop through the main string
for (int i = 0; i <= mainLen - patternLen; ) {
int j;
// Check if pattern exists in the current substring
for (j = 0; j < patternLen; j++) {
if (mainString[i + j] != pattern[j]) {
break;
}
}
if (j == patternLen) {
// Pattern found at position i
// Replace the pattern with the replacement string
for (int k = i; k < i + replaceLen; k++) {
mainString[k] = replace[k - i];
}
// Shift the main string after replacement
for (int k = i + replaceLen; k <= mainLen - patternLen + replaceLen; k++) {
mainString[k] = mainString[k + patternLen - replaceLen];
}
// Update the length of the main string
mainLen -= patternLen - replaceLen;
i += replaceLen;
} else {
// No match, move to the next character
i++;
}
}
}
int main() {
char mainString[1000], pattern[100], replace[100];
printf("Enter the main string: ");
scanf(" %[^\n]", mainString);
printf("Enter the pattern string: ");
scanf("%s", pattern);
printf("Enter the replace string: ");
DEPT OF CSE,TOCE,2023-24 Page 14
DATA STRUCTURES LABORATORY (BCSL305)

scanf("%s", replace);
findAndReplace(mainString, pattern, replace);
printf("Modified string: %s\n", mainString);
return 0;
}

Output
Enter the MAIN string:
good morning
Enter a PATTERN string:
morning
Enter a REPLACE string:
evening
The RESULTANT string is: good evening

1. The findAndReplace function performs the pattern matching and replacement. It searches
for the pattern in the main string and replaces it with the replace string whenever a match is
found.
2. The main function reads the main string, pattern, and replacement string from the user, and
then calls findAndReplace to perform the replacement.

DEPT OF CSE,TOCE,2023-24 Page 15


DATA STRUCTURES LABORATORY (BCSL305)

Program 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

Theory:
Stack is a collection of elements of the similar types. It is also called as last in, first out.
The element inserted first is the last one to be deleted. It is used for various applications like infix
to postfix expression, postfix evaluation and for maintaining stack frames for function calling
 push() - pushing (storing) an element on the stack.
 pop() - removing (accessing) an element from the stack.
To use a stack efficiently we need to check status of stack as well. For the same purpose, the
following functionality is added to stacks;
 peek() − get the top data element of the stack, without removing it.
 isFull() − check if stack is full.
 isEmpty() − check if stack is empty.
Algorithm:
Step 1: Start.
Step 2: Initialize stack size MAX and top of stack -1.
Step 3: Push integer element on to stack and display the contents of the stack.
if stack is full give a message as ‘Stack is Overflow’.
Step 3: Pop element from stack along with display the stack contents.
if stack is empty give a message as ‘Stack is Underflow’.
Step 4: Check whether the stack contents are Palindrome or not.
Step 5: Stop

#include <stdio.h>
#include <stdlib.h>
int stack[6],rev[6];
int top=-1,k=0;
int size;
void push();void pop();
DEPT OF CSE,TOCE,2023-24 Page 16
DATA STRUCTURES LABORATORY (BCSL305)

void display();
int pali();
void main()
{
int choice,f;
printf("Enter the size for stack\n");
scanf("%d",&size);
printf("1.Push\n2.Pop\n3.Display\n4.Check for Palindrome\n5.Exit\n");
while(1)
{
printf("Enter the choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:f=pali();
if(f==1)
printf("It's Palindrome\n");
else
printf("It's not a Palindrome\n");
break;
case 5:exit(0);
default:printf("Wrong choice...\n");
}
}
}
void push()
{
int num;
if(top==(size-1))
{
printf("Stack Overflow\n");
}
else
{
printf("Enter the number to be pushed\n");
scanf("%d",&num);top++;
stack[top]=num;

DEPT OF CSE,TOCE,2023-24 Page 17


DATA STRUCTURES LABORATORY (BCSL305)

}
}
void pop()
{
int num;
if(top==-1)
{
printf("Stack Underflow\n");
}
else
{
num=stack[top];
printf("Popped element is %d\n",num);
top--;
}
}
void display()
{
int i;
if(top==-1)
{
printf("Stack Underflow\n");
}
else
{
printf("Stack Contents....\n");
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
rev[k++]=stack[i];
}
}
}
int pali()
{
int i,flag=1;
for(i=top;i>=0;i--)
{
if(stack[i]!=rev[--k])
{

flag=0;
}

DEPT OF CSE,TOCE,2023-24 Page 18


DATA STRUCTURES LABORATORY (BCSL305)

}
return flag;
}

Output

--------STACK OPERATIONS-----------
1.Push
2.Pop
3.Check for 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:
1
2
1
Enter your choice: 5

DEPT OF CSE,TOCE,2023-24 Page 19


DATA STRUCTURES LABORATORY (BCSL305)

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

Theory:
Infix: Operators are written in-between their operands. Ex: X + Y
Prefix: Operators are written before their operands. Ex: +X Y
postfix: Operators are written after their operands. Ex: XY+
Algorithm:
Step 1: Read the infix expression as a string.
Step 2: Scan the expression character by character till the end. Repeat the following operations
1. If it is an operand add it to the postfix expression.
2. If it is a left parentheses push it onto the stack.
3. If it is a right parentheses pop out elements from the stack and assign it to the
postfix string. Pop out the left parentheses but don’t assign to postfix.
Step 3: If it is an operator compare its precedence with that of the element at the top of
stack.
1.If it is greater push it onto the stack.
2.Else pop and assign elements in the stack to the postfix expression until
you find one such element.
Step 4: If you have reached the end of the expression, pop out any leftover elements in the stack
till it becomes empty.
Step 5: Append a null terminator at the end display the result

#include <stdio.h>
#define SIZE 50
/*
1. Create stack of characters
2. Implement push() and pop()
*/
char s[SIZE];
int top= -1;
void push(char elem)
{
s[++top]=elem;
}
DEPT OF CSE,TOCE,2023-24 Page 20
DATA STRUCTURES LABORATORY (BCSL305)

char pop()
{
return(s[top--]);
}
void display(int k, char p[])
{
for (int i=0; i <= top; i++)
printf("%c", s[i]);
printf("\n");
for (int i=0; i < k; i++)
printf("%c", p[i]);
}
/*
1. Define precedences for the operators
2. The operators are +, -, *, /, ^
3. And lowest for '('
4. Return lowest as default.
*/
int precedence(char elem)
{
switch(elem)
{
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/':
case '%': return 3;
case '^': return 4;
default: return 0;
}
}
/*
1. Input is infix expression
2. Output is postfix e* 6
3. Push the marker '\0'
4. Handle parens, operators and operands
*/
void convert(char infix[], char postfix[])
{
char ch;
int k=0;
push('\0'); // null marker

DEPT OF CSE,TOCE,2023-24 Page 21


DATA STRUCTURES LABORATORY (BCSL305)

for (int i=0; infix[i]; i++)


{
ch = infix[i];
switch(ch)
{
case '(':
push(ch);
break;
case ')':
while((ch = pop()) != '(')
{
postfix[k++] = ch;
}
break;
case '+':
case '-':
case '/':
case '*':
case '%':
case '^':
while(precedence(ch) <= precedence(s[top]))
{
postfix[k++]=pop();
}
push(ch);
break;
default:
postfix[k++]=ch;
}
//display(k, postfix);
}
// empty stack into postfix
// Check if '\0' is at bottom of the stack
while((postfix[k++] = pop()) != '\0');
}
/*
1. Declare infix and postfix arrays
2. Read infix expression
3. Convert infix to postfix expression
*/
int main()
{
char infix[100];

DEPT OF CSE,TOCE,2023-24 Page 22


DATA STRUCTURES LABORATORY (BCSL305)

char postfix[100];
printf("Enter the Infix Expression: ");
scanf("%s",infix);
convert(infix, postfix);
printf("Postfix Expn: %s\n", postfix);
}

Output

Enter the Infix Expression: (a+b)*c

Postfix Expn: ab+c*

DEPT OF CSE,TOCE,2023-24 Page 23


DATA STRUCTURES LABORATORY (BCSL305)

Program 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
Algorithm
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
1.Pop out two operands from stack
2.Apply the operator onto the popped operands.
3.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.
b. TOWER OF HANOI
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of
disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack
in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple
rules:
 Only one disk can be moved at a time.
 Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
 No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves
required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of 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 final pole using the original
pole.

Program 5a:
#include <stdio.h>
#include <stdlib.h>

DEPT OF CSE,TOCE,2023-24 Page 24


DATA STRUCTURES LABORATORY (BCSL305)

#include <ctype.h>
#include <math.h>
#include <string.h>
#define SIZE 50 /* Size of Stack */
int stack[SIZE];
int top = -1;
void push(int elem)
{
stack[++top]=elem;
}
int pop()
{
return(stack[top--]);
}
/*
1. Input is postfix expression as string
2. Push operands until the operator
3. evaluate exp with this operator and operands on the stack
4. Push the result on to the stack
*/
void suffix()
{
char exp[50];
char ch;
printf("Enter suffix exression:");
scanf("%s", exp);
for (int i=0; exp[i]; i++)
{
ch = exp[i];
switch(ch)
{
case '+':
push(pop()+pop());
break;
case '-':
push(pop()-pop());
break;
case '*':
push(pop()*pop());
break;
case '/':
push(pop()/pop());
break;

DEPT OF CSE,TOCE,2023-24 Page 25


DATA STRUCTURES LABORATORY (BCSL305)

case '%':
push(pop()%pop());
break;
case '^': push(pow(pop(), pop()));
break;
default:
push(ch-'0'); /* Push the operand */
}
}
printf("Result: %d, top=%d\n\n", pop(), top);
}
/*
1. Inputs are number of disks and 3 pegs 'b', 'a', and 'e'
2. Base case when n = 1, move b -> e
3. when n=2, b -> e, b -> a, a -> e
*/
void toh(int n, char beg, char aux, char end)
{
if(n == 1)
{
printf("%c --> %c\n", beg, end);
return;
}
toh(n-1, beg, end, aux);
toh(1, beg, aux, end);
toh(n-1, aux, beg, end);
}
void tower()
{
int n;
printf("Enter number of disks: ");
scanf("%d", &n);
toh(n, 'b', 'a', 'e');
}
/*
1. Evaluate postfix expression one or more times
2. Stop evaluation when the expressio is '.'
3. Solve tower of hanoi until the number diskes is 0
*/
int main()
{
int choice;
struct MENU

DEPT OF CSE,TOCE,2023-24 Page 26


DATA STRUCTURES LABORATORY (BCSL305)

{
char *name; void (*func)();
} menu[] = {
{"Done", exit },
{"Suffix", suffix},
{"Tower", tower }
};
int size = sizeof(menu)/sizeof(menu[0]);
for(;;)
{
printf("\n-------Array Menu-------\n");
for(int i=1; i < size; i++)
{
printf("%d. %s\n", i, menu[i].name);
}
printf("---------------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
menu[choice].func();
}
return 0;
}

OUTPUT

-------Array Menu-------

1. Suffix

2. Tower

---------------------------------

Enter your choice: 1

Enter suffix exression:22*32^1

Result: 1, top=2

-------Array Menu-------

1. Suffix

2. Tower

DEPT OF CSE,TOCE,2023-24 Page 27


DATA STRUCTURES LABORATORY (BCSL305)

---------------------------------

Enter your choice: 2

Enter number of disks: 3

b --> e

b --> a

e --> a

b --> e

a --> b

a --> e

b --> e

-------Array Menu-------

1. Suffix

2. Tower

-------------------------------

-------Array Menu-------

1. Suffix

2. Tower

DEPT OF CSE,TOCE,2023-24 Page 28


DATA STRUCTURES LABORATORY (BCSL305)

Program 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
Theory:
Circular queue is a linear data structure. It follows FIFO principle. In circular queue the last node
is connected back to the first node to make a circle.It is also called FIFO structure. Elements are
added at the rear end and the elements are deleted at front end of the queue. The queue is
considered as a circular queue when the positions 0 and MAX-1 are adjacent.
ALGORITHM:
Step 1: Start.
Step 2: Initialize queue size to MAX.
Step 3: Insert the elements into circular queue. If queue is full give a message as ‘queue is
overflow”
Step 4: Delete an element from the circular queue. If queue is empty give a message as ‘queue is
underflow’.
Step 5: Display the contents of the queue.
Step 6: Stop.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 5
char CQ[SIZE];
int front=-1, rear=-1;

DEPT OF CSE,TOCE,2023-24 Page 29


DATA STRUCTURES LABORATORY (BCSL305)

int ch;
void CQ_Insert();
void CQ_Delet();
void CQ_Display();
void main()
{
printf("1.Insert\n2.Delete\n3.Display\n4.Exit\n");
while(1)
{
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: CQ_Insert();
break;
case 2:CQ_Delet();
break;
case 3:CQ_Display();
break;
case 4: exit(0);
}
}
}
void CQ_Insert()
{

DEPT OF CSE,TOCE,2023-24 Page 30


DATA STRUCTURES LABORATORY (BCSL305)

char ele;
if(front==(rear+1)%SIZE)
{
printf("Circular Queue Full\n");
return;
}
if(front==-1)
front++;
printf("Enter the element to be inserted\n");
scanf("\n%c",&ele);
rear = (rear+1)%SIZE;
CQ[rear] =ele;
}
void CQ_Delet()
{
char item;
if(front == -1)
{
printf("Circular Queue Empty\n");
return;
}
else if(front == rear)
{
item=CQ[front];
printf("Deleted element is: %c\n",item);

DEPT OF CSE,TOCE,2023-24 Page 31


DATA STRUCTURES LABORATORY (BCSL305)

front=-1;
rear=-1;
}
else
{
item =CQ[front];
printf("Deleted element is: %c\n",item);
front = (front+1)%SIZE;
}
}
void CQ_Display()
{
int i;
if(front==-1)
printf("Circular Queue is Empty\n");
else
{
printf("Elements of the circular queue are..\n");
for(i=front;i!=rear;i=(i+1)%SIZE)
{
printf("%c\t",CQ[i]);
}
printf("%c\n",CQ[i]);
}
}

DEPT OF CSE,TOCE,2023-24 Page 32


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: a
Enter your choice:1
Enter element to be insert: b
Enter your choice:1
Enter element to be insert: c
Enter your choice:3
abc
Enter your choice:2
Deleted element is: a
Enter your choice:3
bc
Enter your choice:4

DEPT OF CSE,TOCE,2023-24 Page 33


DATA STRUCTURES LABORATORY (BCSL305)

Program 7:

Develop a menu driven Program in C for the following operations on Singly Linked List
(SLL) of Student Data with the fields: USN, Name, Programme, Sem,PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit

#include <stdio.h>
#include <stdlib.h>
typedef struct NODE Node;
struct NODE
{
char usn[20];
char name[20];
char branch[20];
char sem[20];
char phone[20];
Node *next;
};
Node *start = NULL;
int flag=0; /* is 1 when list is created */
void get(char *prompt, char *s)
{
printf("Enter %s:", prompt);
scanf("%s", s);
}
Node *info()
{
Node *s;
s = malloc(sizeof(Node));
get("USN", s->usn);
get("Name", s->name);
get("Branch", s->branch);
get("Semester", s->sem);
get("Phone", s->phone);
s->next = NULL;
return(s);
DEPT OF CSE,TOCE,2023-24 Page 34
DATA STRUCTURES LABORATORY (BCSL305)

}
void insert_front()
{
Node *student;
student = info();
if (start == NULL)
{
student->next = NULL;
start = student;
return;
}
student->next = start;
start = student;
}
void insert_end()
{
Node *p, *student;
student = info();
student->next = NULL;
if (start == NULL)
{
start = student;
return;
}
p = start;
while(p->next != NULL)
{
p = p->next;
}
p->next = student;
}
void delete_front()
{
Node *p;
if (start == NULL)
{
printf("The list is empty. \n");
return;
}
p = start;
start = start->next;
printf("Deleted Student USN is %s \n\n", p->usn);
free(p);

DEPT OF CSE,TOCE,2023-24 Page 35


DATA STRUCTURES LABORATORY (BCSL305)

}
void delete_end()
{
Node *p, *q;
if (start == NULL)
{
printf("The list is empty. \n");
return;
}
if (start->next == NULL)
{
printf("Deleted Student USN is %s \n\n", start->usn);
free(start);
start=NULL;
return;
}
p = start;
while (p->next != NULL)
{
q = p;
p = p->next;
}
q->next = p->next;
printf("Deleted Student USN is %s \n\n", p->usn);
free(p);
}
void display()
{
Node *p;
int n;
p = start;
n = 1;
while(p != NULL)
{
printf("%d. %s %s %s %s %s\n", n, p->usn, p->name, p->branch, p->sem, p->phone);
p = p->next;
n++;
}
}
void create()
{
int n;
printf("Enter number of students: ");

DEPT OF CSE,TOCE,2023-24 Page 36


DATA STRUCTURES LABORATORY (BCSL305)

scanf("%d", &n);
for(int i=1; i <= n; i++)
{
printf("\nStudent %d details\n", i);
insert_front();
}
}
int main()
{
int choice;
struct MENU
{
char *name;
void (*func)();
} menu[] = {
{"Done", exit},
{"Create", create},
{"Insert front", insert_front},
{"Insert end", insert_end},
{"Delete front", delete_front},
{"Delete end", delete_end},
{"Display", display}
};
int size = sizeof(menu)/sizeof(menu[0]);
for(;;)
{
printf("\n-------SLL Menu-------\n");
for(int i=1; i < size; i++)
{
printf("%d. %s\n", i, menu[i].name);
}
printf("---------------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
menu[choice].func();
}
}Output

-------SLL Menu-------
1. Create
2. Insert front
3. Insert end
DEPT OF CSE,TOCE,2023-24 Page 37
DATA STRUCTURES LABORATORY (BCSL305)

4. Delete front
5. Delete end
6. Display
---------------------------------
Enter your choice: 1
Enter number of students: 1

Student 1 details
Enter USN:34
Enter Name:anu
Enter Branch:cse
Enter Semester:2
Enter Phone:234567

-------SLL Menu-------
1. Create
2. Insert front
3. Insert end
4. Delete front
5. Delete end
6. Display
---------------------------------
Enter your choice: 2
Enter USN:23
Enter Name:priya
Enter Branch:cse
Enter Semester:2
Enter Phone:342342

-------SLL Menu-------
1. Create
2. Insert front
3. Insert end
4. Delete front
5. Delete end
6. Display
---------------------------------
Enter your choice: 6
1. 23 priya cse 2 342342
2. 34 anu cse 2 234567

-------SLL Menu-------
1. Create

DEPT OF CSE,TOCE,2023-24 Page 38


DATA STRUCTURES LABORATORY (BCSL305)

2. Insert front
3. Insert end
4. Delete front
5. Delete end
6. Display
---------------------------------
Enter your choice:

DEPT OF CSE,TOCE,2023-24 Page 39


DATA STRUCTURES LABORATORY (BCSL305)

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

#include<string.h>

#include<stdio.h>

#include<stdlib.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];

DEPT OF CSE,TOCE,2023-24 Page 40


DATA STRUCTURES LABORATORY (BCSL305)

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;

temp->phno = phno;

count++;}

void insertbeg()

if (h == NULL)

create();

h = temp;

temp1 = h;

else

create();

DEPT OF CSE,TOCE,2023-24 Page 41


DATA STRUCTURES LABORATORY (BCSL305)

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()

DEPT OF CSE,TOCE,2023-24 Page 42


DATA STRUCTURES LABORATORY (BCSL305)

temp2 =h;

if(temp2 == NULL)

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);
DEPT OF CSE,TOCE,2023-24 Page 43
DATA STRUCTURES LABORATORY (BCSL305)

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)
{
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);
}
DEPT OF CSE,TOCE,2023-24 Page 44
DATA STRUCTURES LABORATORY (BCSL305)

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;
case 2:
displaybeg();
break;
case 3:
insertend();
break;
case 4:
DEPT OF CSE,TOCE,2023-24 Page 45
DATA STRUCTURES LABORATORY (BCSL305)

deleteend();
break;
case 5:
insertbeg(); break;
case 6:
deletebeg();
break;
case 7:
exit(0);
default:
printf("wrong choice\n");
}
}
}
Output
linux:~/dslab #gedit
dlink.c linux:~/dslab
#gcc dlink.c
linux:~/dslab # ./a.out
---
---
---
---
---
-- 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 :
DEPT OF CSE,TOCE,2023-24 Page 46
DATA STRUCTURES LABORATORY (BCSL305)

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 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
DEPT OF CSE,TOCE,2023-24 Page 47
DATA STRUCTURES LABORATORY (BCSL305)

Exit

Program 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
Circular Linked List is a variation of Linked list in which first element points to last element and
last element points to first element. Both Singly Linked List and Doubly Linked List can be
made into as circular linked list.
Adding two polynomials are represented using linked lists
Representation of a Polynomial: A polynomial is an expression that contains
more than two terms. A term is made up of coefficient and exponent.
An example of polynomial is
P(x) = 4x3+6x2+7x+9
A polynomial thus may be represented using arrays or linked lists. Array representation assumes
that the exponents of the given expression are arranged from 0 to the highest value (degree),
which is represented by the subscript of the array beginning with 0. The coefficients of the
respective exponent are placed at an appropriate index in the array. The array representation for
the above polynomial expression is given below:

A polynomial may also be represented using a linked list. A structure may be defined such that
it contains two parts- one is the coefficient and second is the corresponding exponent. The
structure definition may be given as shown below:
struct polynomial
{
int coefficient;
int exponent;
struct polynomial *next;
};

Addition of two Polynomials:


For adding two polynomials using arrays is straightforward method, since both the arrays may be
added up element wise beginning from 0 to n-1, resulting in addition of two polynomials.
Addition of two polynomials using linked list requires comparing the exponents, and wherever
the exponents are found to be same, the coefficients are added up. For terms with different
exponents, the complete term is simply added to the result thereby making it a part of addition
result. The complete program to add two polynomials is given in subsequent section.

#include<stdio.h>
DEPT OF CSE,TOCE,2023-24 Page 48
DATA STRUCTURES LABORATORY (BCSL305)

#include<malloc.h>
#include<math.h>
#include<stdlib.h>
struct node
{
int cf, px, py, pz;
int flag;
struct node *link;
};
typedef struct node NODE;
NODE* getnode()
{
NODE *x;
x=(NODE*)malloc(sizeof(NODE));
if(x==NULL)
{
printf("Insufficient memory\n");
exit(0);
}
return x;
}
void display(NODE *head)
{
NODE *temp;
if(head->link==head)
{
printf("Polynomial does not exist\n");
return;
}
temp=head->link;
printf("\n");
while(temp!=head)
{
printf("%d x^%d y^%d z^%d",temp->cf,temp->px,temp->py,temp-
>pz);
if(temp->link != head)
printf(" + ");
temp=temp->link;
DEPT OF CSE,TOCE,2023-24 Page 49
DATA STRUCTURES LABORATORY (BCSL305)

}
printf("\n");
}
NODE* insert_rear(int cf,int x,int y,int z,NODE *head)
{
NODE *temp,*cur;
temp=getnode();
temp->cf=cf;
temp->px=x;
temp->py=y;
temp->pz=z;
cur=head->link;
while(cur->link!=head)
{
cur=cur->link;
}
cur->link=temp;
temp->link=head;
return head;
}
NODE* read_poly(NODE *head)
{
int px, py, pz, cf, ch;
printf("\nEnter coeff: ");
scanf("%d",&cf);
printf("\nEnter x, y, z powers(0-indiacate NO term): ");
scanf("%d%d%d", &px, &py, &pz);
head=insert_rear(cf,px,py,pz,head);
printf("\nIf you wish to continue press 1 otherwise 0: ");
scanf("%d", &ch);
while(ch != 0)
{
printf("\nEnter coeff: ");
scanf("%d",&cf);
printf("\nEnter x, y, z powers(0-indiacate NO term): ");
scanf("%d%d%d", &px, &py, &pz);
head=insert_rear(cf,px,py,pz,head);
printf("\nIf you wish to continue press 1 otherwise 0: ");
DEPT OF CSE,TOCE,2023-24 Page 50
DATA STRUCTURES LABORATORY (BCSL305)

scanf("%d", &ch);
}
return head;
}
NODE* add_poly(NODE *h1,NODE *h2,NODE *h3)
{
NODE *p1,*p2;
int x1,x2,y1,y2,z1,z2,cf1,cf2,cf;
p1=h1->link;
while(p1!=h1)
{
x1=p1->px;
y1=p1->py;
z1=p1->pz;
cf1=p1->cf;
p2=h2->link;
while(p2!=h2)
{
x2=p2->px;
y2=p2->py;
z2=p2->pz;
cf2=p2->cf;
if(x1==x2 && y1==y2 && z1==z2)break;
p2=p2->link;
}
if(p2!=h2)
{
cf=cf1+cf2;
p2->flag=1;
if(cf!=0)
h3=insert_rear(cf,x1,y1,z1,h3);
}
else
h3=insert_rear(cf1,x1,y1,z1,h3);
p1=p1->link;
}
p2=h2->link;
while(p2!=h2)
DEPT OF CSE,TOCE,2023-24 Page 51
DATA STRUCTURES LABORATORY (BCSL305)

{
if(p2->flag==0)
h3=insert_rear(p2->cf,p2->px,p2->py,p2->pz,h3);
p2=p2->link;
}
return h3;
}
void evaluate(NODE *h1)
{
NODE *head;
int x, y, z;
float result=0.0;
head=h1;
printf("\nEnter x, y, z, terms to evaluate:\n");
scanf("%d%d%d", &x, &y, &z);
while(h1->link != head)
{
result = result + (h1->cf * pow(x,h1->px) * pow(y,h1->py) *
pow(z,h1->pz));
h1=h1->link;
}
result = result + (h1->cf * pow(x,h1->px) * pow(y,h1->py) *
pow(z,h1->pz));
printf("\nPolynomial result is: %f", result);
}
int main()
{
NODE *h1,*h2,*h3;
int ch;
h1=getnode();
h2=getnode();
h3=getnode();
h1->link=h1;
h2->link=h2;
h3->link=h3;
while(1)
{
printf("\n\n1.Evaluate polynomial\n2.Add two
DEPT OF CSE,TOCE,2023-24 Page 52
DATA STRUCTURES LABORATORY (BCSL305)

polynomials\n3.Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("\nEnter polynomial to evaluate:\n");
h1=read_poly(h1);
display(h1);
evaluate(h1);
break;
case 2:
printf("\nEnter the first polynomial:");
h1=read_poly(h1);
printf("\nEnter the second polynomial:");
h2=read_poly(h2);
h3=add_poly(h1,h2,h3);
printf("\nFirst polynomial is: ");
display(h1);
printf("\nSecond polynomial is: ");
display(h2);
printf("\nThe sum of 2 polynomials is: ");
display(h3);
break;
case 3:
exit(0); break;
default:
printf("\nInvalid entry");
break;
}
}
}

Output:
1. Evaluate polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
2. Add two polynomials
3. Exit

DEPT OF CSE,TOCE,2023-24 Page 53


DATA STRUCTURES LABORATORY (BCSL305)

Enter your choice: 1


Enter polynomial to evaluate:
Enter coeff: 6 Enter x, y, z powers (0-indiacate NO term: 2 2 1
If you wish to continue press 1 otherwise 0: 1
Enter coeff: -4 Enter x, y, z powers (0-indiacate NO term: 0 1 5
If you wish to continue press 1 otherwise 0: 1
Enter coeff: 3
Enter x, y, z powers (0-indiacate NO term: 3 1 1
If you wish to continue press 1 otherwise 0: 1
Enter coeff: 2
x, y, z powers (0-indiacate NO term: 1 5 1
If you wish to continue press 1 otherwise 0: 1
Enter coeff: -2
Enter x, y, z powers (0-indiacate NO term: 1 1 3
If you wish to continue press 1 otherwise 0: 0
Polynomial is: 6 x^2 y^2 z^1 + -4 x^0 y^1 z^5 + 3 x^3 y^1 z^1 + 2 x^1 y^5 z^1 + -2 x^1 y^1 z^3
Enter x, y, z, terms to evaluate: 1 1 1
Polynomial result is: 5.000000
1. Evaluate polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
2. Add two polynomials
3. Exit Enter your choice: 2
Enter 1st polynomial: Enter coeff: 4
Enter x, y, z powers (0-indiacate NO term: 2 2 2
If you wish to continue press 1 otherwise 0: 1
Enter coeff: 3 Enter x, y, z powers (0-indiacate NO term: 1 1 2
If you wish to continue press 1 otherwise 0: 0
Enter 2nd polynomial: Enter coeff: 6
Enter x, y, z powers (0-indiacate NO term: 2 2 2
If you wish to continue press 1 otherwise 0: 0
Polynomial is: 1st Polynomial is: 4 x^2 y^2 z^2 + 3 x^1 y^1 z^2
2nd Polynomial is: 6 x^2 y^2 z^2 Added polynomial: 10 x^2 y^2 z^2 + 3 x^1 y^1 z^2 1.
Evaluate polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
2. Add two polynomials 3. Exit Enter your choice: 3

DEPT OF CSE,TOCE,2023-24 Page 54


DATA STRUCTURES LABORATORY (BCSL305)

Program 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
A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties −
 The left sub-tree of a node has key less than or equal to its parent node's key.
 The right sub-tree of a node has key greater than or equal to its parent node's key.
Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-tree and
right sub-tree and can be defined as −
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

Basic Operations
Following are basic primary operations of a tree which are following.
 Search − search an element in a tree.
 Insert − insert an element in a tree.
 Preorder Traversal − traverse a tree in a preorder manner.
 Inorder Traversal − traverse a tree in an inorder manner.
 Postorder Traversal − traverse a tree in a postorder manner.

#include <stdio.h>
#include <stdlib.h>
struct BST
{
int data;
struct BST *left;
struct BST *right;
};
typedef struct BST NODE;
NODE *node;
NODE* createtree(NODE *node, int data)
{
if (node == NULL)
{

DEPT OF CSE,TOCE,2023-24 Page 55


DATA STRUCTURES LABORATORY (BCSL305)

NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if (data < (node->data))
{
node->left = createtree(node->left, data);
}
else if (data > node->data)
{
node -> right = createtree(node->right, data);
}
return node;
}
NODE* search(NODE *node, int data)
{
if(node == NULL)
printf("\nElement not found");
else if(data < node->data)
{
node->left=search(node->left, data);
}
else if(data > node->data)
{
node->right=search(node->right, data);
}
else
printf("\nElement found is: %d", node->data);
return node;
}
void inorder(NODE *node)
{
if(node != NULL)
{
inorder(node->left);
printf("%d\t", node->data);
DEPT OF CSE,TOCE,2023-24 Page 56
DATA STRUCTURES LABORATORY (BCSL305)

inorder(node->right);
}
}
void preorder(NODE *node)
{
if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}
void postorder(NODE *node)
{
if(node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d\t", node->data);
}
}
NODE* findMin(NODE *node)
{
if(node==NULL)
{
return NULL;
}
if(node->left)
return findMin(node->left);
else
return node;
}
int main()
{
int data, ch, i, n;
NODE *root=NULL;
while (1)
{
DEPT OF CSE,TOCE,2023-24 Page 57
DATA STRUCTURES LABORATORY (BCSL305)

printf("\n1.Insertion in Binary Search Tree");


printf("\n2.Search Element in Binary Search Tree");
printf("\n3.Inorder\n4.Preorder\n5.Postorder\n6.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\nEnter N value: " );
scanf("%d", &n);
printf("\nEnter the values to create BST like(6,9,5,2,8,15,24,14,7,8,5,2)\n");
for(i=0; i<n; i++)
{
scanf("%d", &data);
root=createtree(root, data);
}
break;
case 2: printf("\nEnter the element to search: ");
scanf("%d", &data);
root=search(root, data);
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("\nWrong option");
break;
}
}
}

Output:
1. Insertion in Binary Search Tree
DEPT OF CSE,TOCE,2023-24 Page 58
DATA STRUCTURES LABORATORY (BCSL305)

2. Search Element in Binary Search Tree


3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice: 1
Enter N value: 12 Enter the values to create BST like(6,9,5,2,8,15,24,14,7,8,5,2)
6 9 5 2 8 15 24 14 7 8 5 2
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice: 3
Inorder Traversal: 2 5 6 7 8 9 14 15 24
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice: 4
Preorder Traversal: 6 5 2 9 8 7 15 14 24
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice: 5
Postorder Traversal: 2 5 7 8 14 24 15 9 6
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Inorder
4. Preorder
5. Postorder
6. Exit
DEPT OF CSE,TOCE,2023-24 Page 59
DATA STRUCTURES LABORATORY (BCSL305)

Enter your choice: 2


Enter the element to search: 24
Element found is: 24
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Inorder
4. Preorder
5. Postorder
6. Exit
Enter your choice: 2
Enter the element to search: 50
Element not found
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Inorder
4. Preorder
5. Postorder
6. Exit Enter your choice: 6

DEPT OF CSE,TOCE,2023-24 Page 60


DATA STRUCTURES LABORATORY (BCSL305)

Program 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
Depth-first search (DFS)
There are various ways to traverse (visit all the nodes) of a graph systematically. A couple of
these ways (depth-first and breadth-first) give us some information about graph structure (e.g.
connectedness).
In depth-first search the idea is to travel as deep as possible from neighbour to neighbour before
backtracking. What determines how deep is possible is that you must follow edges, and you don't
visit any vertex twice.
To do this properly we need to keep track of which vertices have already been visited, plus how
we got to (the path to...) where we currently are, so that we can backtrack. We could keep track
of which nodes were visited in a boolean array, and a stack to push nodes onto that we mean to
visit (the course Readings have a recursive algorithm for DFS which takes a slightly different
approach).

#include<stdio.h>
#include<stdlib.h>
int a[10][10], n, m, i, j, source, s[10], b[10];
int visited[10];
void create()
{
printf("\nEnter the number of vertices of the digraph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix of the graph:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d", &a[i][j]);
}
void bfs()
{

DEPT OF CSE,TOCE,2023-24 Page 61


DATA STRUCTURES LABORATORY (BCSL305)

int q[10], u, front=0, rear=-1;


printf("\nEnter the source vertex to find other nodes reachable or not: ");
scanf("%d", &source);
q[++rear] = source;
visited[source] = 1;
printf("\nThe reachable vertices are: ");
while(front<=rear)
{
u = q[front++];
for(i=1; i<=n; i++)
{
if(a[u][i] == 1 && visited[i] == 0)
{
q[++rear] = i;
visited[i] = 1;
printf("\n%d", i);
}
}
}
}
void dfs(int source)
{
int v, top = -1;
s[++top] = 1;
b[source] = 1;
for(v=1; v<=n; v++)
{
if(a[source][v] == 1 && b[v] == 0)
{
printf("\n%d -> %d", source, v);
dfs(v);
}
}
}
int main()
{
int ch;
while(1)
DEPT OF CSE,TOCE,2023-24 Page 62
DATA STRUCTURES LABORATORY (BCSL305)

{
printf("\n1.Create Graph\n2.BFS\n3.Check graph connected or not(DFS)\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: create();
break;
case 2: bfs();
for(i=1;i<=n;i++)
if(visited[i]==0)
printf("\nThe vertex that is not rechable %d" ,i);
break;
case 3: printf("\nEnter the source vertex to find the connectivity: ");
scanf("%d",&source);
m=1;
dfs(source);
for(i=1;i<=n;i++) {
if(b[i]==0)
m=0;
}
if(m==1)
printf("\nGraph is Connected");
else
printf("\nGraph is not Connected");
break;
default: exit(0);
}
}
}

OUTPUT:
1. Create Graph
2.BFS
3.Check graph connected or not (DFS)
4.Exit
Enter your choice: 1
Enter the number of vertices of the digraph: 5

DEPT OF CSE,TOCE,2023-24 Page 63


DATA STRUCTURES LABORATORY (BCSL305)

Enter the adjacency matrix of the graph:


01110
10011
10010
11101
01010

1. Create Graph
2.BFS
3.Check graph connected or not (DFS)
4.Exit
Enter your choice: 2
Enter the source vertex to find other nodes reachable or not: 1
2345
1. Create Graph
2.BFS
3.Check graph connected or not (DFS)
4.Exit
Enter your choice: 3
Enter the source vertex to find the connectivity: 1
1 -> 2
2 -> 4
4 -> 3
4->5
Graph is Connected
1. Create Graph 2.BFS 3.Check graph connected or not (DFS) 4.Exit Enter your choice:
4

DEPT OF CSE,TOCE,2023-24 Page 64


DATA STRUCTURES LABORATORY (BCSL305)

Program 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.
Direct-address table
If the keys are drawn from the reasoning small universe U = {0, 1, . . . , m-1} of keys, a solution
is to use a Table T[0, . m-1], indexed by keys. To represent the dynamic set, we use an array, or
direct-address table, denoted by T[0 . . m-1], in which each slot corresponds to a key in the
universe.

Following figure illustrates the approach.

Each key in the universe U i.e., Collection, corresponds to an index in the table T[0 . . m-1].
Using this approach, all three basic operations (dictionary operations) take θ(1) in the worst case.

DEPT OF CSE,TOCE,2023-24 Page 65


DATA STRUCTURES LABORATORY (BCSL305)

Hash Tables
When the size of the universe is much larger the same approach (direct address table) could still
work in principle, but the size of the table would make it impractical. A solution is to map the
keys onto a small range, using a function called a hash function. The resulting data structure is
called hash table.
With direct addressing, an element with key k is stored in slot k. With hashing =, this same
element is stored in slot h(k); that is we use a hash function h to compute the slot from the key.
Hash function maps the universe U of keys into the slot of a hash table T[0 . . .m-1].
h: U → {0, 1, . . ., m-1}
More formally, suppose we want to store a set of size n in a table of size m. The ratio α = n/m is
called a load factor, that is, the average number of elements stored in a Table. Assume we have a
hash function h that maps each key k U to an integer name h(k) [0 . . m-1]. The basic idea is
to store key k in location T[h(k)].
Typical, hash functions generate "random looking" valves. For example, the following function
usually works well
h(k) = k mod m where m is a prime number.
Is there any point of the hash function? Yes, the point of the hash function is to reduce the range
of array indices that need to be handled.
Collision
As keys are inserted in the table, it is possible that two keys may hash to the same table slot. If
the hash function distributes the elements uniformly over the table, the number of conclusions
cannot be too large on the average, but the birthday paradox makes it very likely that there will
be at least one collision, even for a lightly loaded table

A hash function h map the keys k and j to the same slot, so they collide.

DEPT OF CSE,TOCE,2023-24 Page 66


DATA STRUCTURES LABORATORY (BCSL305)

There are two basic methods for handling collisions in a hash table: Chaining and Open
addressing.

#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);
}
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;
DEPT OF CSE,TOCE,2023-24 Page 67
DATA STRUCTURES LABORATORY (BCSL305)

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

DEPT OF CSE,TOCE,2023-24 Page 68


DATA STRUCTURES LABORATORY (BCSL305)

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;
}}}

Output

linux:~/dslab #gedit
hash.c linux:~/dslab
#gcc hash.c
linux:~/dslab # ./a.out
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

DEPT OF CSE,TOCE,2023-24 Page 69


DATA STRUCTURES LABORATORY (BCSL305)

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
100

DEPT OF CSE,TOCE,2023-24 Page 70


DATA STRUCTURES LABORATORY (BCSL305)

13.Viva Questions
1) What is data structure?

Data structures refers to the way data is organized and manipulated. It seeks to find ways to make data
access more efficient. When dealing with data structure, we not only focus on one piece of data, but rather
different set of data and how they can relate to one another in an organized manner.

2) Differentiate file structure from storage structure.

Basically, the key difference is the memory area that is being accessed. When dealing with the structure
that resides the main memory of the computer system, this is referred to as storage structure. When
dealing with an auxiliary structure, we refer to it as file structures.

3) When is a binary search best applied?

A binary search is an algorithm that is best applied to search a list when the elements are already in order
or sorted. The list is search starting in the middle, such that if that middle value is not the target search
key, it will check to see if it will continue the search on the lower half of the list or the higher half. The
split and search will then continue in the same manner.

4) What is a linked list?

A linked list is a sequence of nodes in which each node is connected to the node following it. This forms
a chain-like link of data storage.

5) How do you reference all the elements in a one-dimension array?

To do this, an indexed loop is used, such that the counter runs from 0 to the array size minus one. In this
manner, we are able to reference all the elements in sequence by using the loop counter as the array
subscript.

6) In what areas do data structures applied?

DEPT OF CSE,TOCE,2023-24 Page 71


DATA STRUCTURES LABORATORY (BCSL305)

Data structures is important in almost every aspect where data is involved. In general, algorithms that
involve efficient data structure is applied in the following areas: numerical analysis, operating system,
A.I., compiler design, database management, graphics, and statistical analysis, to name a few.

7) What is LIFO?

LIFO is short for Last In First Out, and refers to how data is accessed, stored and retrieved. Using this
scheme, data that was stored last , should be the one to be extracted first. This also means that in order to
gain access to the first data, all the other data that was stored before this first data must first be retrieved
and extracted.

8 ) What is a queue?

A queue is a data structures that can simulates a list or stream of data. In this structure, new elements are
inserted at one end and existing elements are removed from the other end.

9) What are binary trees?

A binary tree is one type of data structure that has two nodes, a left node and a right node. In
programming, binary trees are actually an extension of the linked list structures.

10) Which data structures is applied when dealing with a recursive function?

Recursion, which is basically a function that calls itself based on a terminating condition, makes use of
the stack. Using LIFO, a call to a recursive function saves the return address so that it knows how to
return to the calling function after the call terminates.

11) What is a stack?

A stack is a data structure in which only the top element can be accessed. As data is stored in the stack,
each data is pushed downward, leaving the most recently added data on top.

12) Explain Binary Search Tree

A binary search tree stores data in such a way that they can be retrieved very efficiently. The left subtree
contains nodes whose keys are less than the node’s key value, while the right subtree contains nodes
whose keys are greater than or equal to the node’s key value. Moreover, both subtrees are also binary
search trees.

13) What are multidimensional arrays?

DEPT OF CSE,TOCE,2023-24 Page 72


DATA STRUCTURES LABORATORY (BCSL305)

Multidimensional arrays make use of multiple indexes to store data. It is useful when storing data that
cannot be represented using a single dimensional indexing, such as data representation in a board game,
tables with data stored in more than one column.

14) Are linked lists considered linear or non-linear data structures?

It actually depends on where you intend to apply linked lists. If you based it on storage, a linked list is
considered non-linear. On the other hand, if you based it on access strategies, then a linked list is
considered linear.

15) How does dynamic memory allocation help in managing data?

Aside from being able to store simple structured data types, dynamic memory allocation can combine
separately allocated structured blocks to form composite structures that expand and contract as needed.

16) What is FIFO?

FIFO is short for First-in, First-out, and is used to represent how data is accessed in a queue. Data has
been inserted into the queue list the longest is the one that is removed first.

17) What is an ordered list?

An ordered list is a list in which each node’s position in the list is determined by the value of its key
component, so that the key values form an increasing sequence, as the list is traversed.

18) What is merge sort?

Merge sort takes a divide-and-conquer approach to sorting data. In a sequence of data, adjacent ones are
merged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an even
bigger sorted list, which continuous until you have one single sorted list.

19) Differentiate NULL and VOID.

Null is actually a value, whereas Void is a data type identifier. A variable that is given a Null value
simply indicates an empty value. Void is used to identify pointers as having no initial size.

20) What is the primary advantage of a linked list?

A linked list is a very ideal data structure because it can be modified easily. This means that modifying a
linked list works regardless of how many elements are in the list.

21) What is the difference between a PUSH and a POP?

DEPT OF CSE,TOCE,2023-24 Page 73


DATA STRUCTURES LABORATORY (BCSL305)

Pushing and popping applies to the way data is stored and retrieved in a stack. A push denotes data being
added to it, meaning data is being “pushed” into the stack. On the other hand, a pop denotes data retrieval,
and in particular refers to the topmost data being accessed.

22) What is a linear search?

A linear search refers to the way a target key is being searched in a sequential data structure. Using this
method, each element in the list is checked and compared against the target key, and is repeated until
found or if the end of the list has been reached.

23) How does variable declaration affect memory allocation?

The amount of memory to be allocated or reserved would depend on the data type of the variable being
declared. For example, if a variable is declared to be of integer type, then 32 bits of memory storage will
be reserved for that variable.

24) What is the advantage of the heap over a stack?

Basically, the heap is more flexible than the stack. That’s because memory space for the heap can be
dynamically allocated and de-allocated as needed. However, memory of the heap can at times be slower
when compared to that stack.

25) What is a postfix expression?

A postfix expression is an expression in which each operator follows its operands. The advantage of this
form is that there is no need to group sub-expressions in parentheses or to consider operator precedence.
26) What is Data abstraction?

Data abstraction is a powerful tool for breaking down complex data problems into manageable chunks.
This is applied by initially specifying the data objects involved and the operations to be performed on
these data objects without being overly concerned with how the data objects will be represented and
stored in memory.

27) How do you insert a new item in a binary search tree?

Assuming that the data to be inserted is a unique value (that is, not an existing entry in the tree), check
first if the tree is empty. If it’s empty, just insert the new item in the root node. If it’s not empty, refer to
the new item’s key. If it’s smaller than the root’s key, insert it into the root’s left subtree, otherwise, insert
it into the root’s right subtree.

28) How does a selection sort work for an array?

The selection sort is a fairly intuitive sorting algorithm,, though not necessarily efficient. To perform this,
the smallest element is first located and switched with the element at subscript zero, thereby placing the
smallest element in the first position. The smallest element remaining in the subarray is then located next

DEPT OF CSE,TOCE,2023-24 Page 74


DATA STRUCTURES LABORATORY (BCSL305)

with subscripts 1 through n-1 and switched with the element at subscript 1, thereby placing the second
smallest element in the second position. The steps are repeated in the same manner till the last element.

29) How do signed and unsigned numbers affect memory?

In the case of signed numbers, the first bit is used to indicate whether positive or negative, which leaves
you with one bit short. With unsigned numbers, you have all bits available for that number. The effect is
best seen in the number range (unsigned 8 bit number has a range 0-255, while 8-bit signed number has a
range -128 to +127.

30) What is the minimum number of nodes that a binary tree can have?

A binary tree can have a minimum of zero nodes, which occurs when the nodes have NULL values.
Furthermore, a binary tree can also have 1 or 2 nodes.

31) What are dynamic data structures?

Dynamic data structures are structures that expand and contract as a program runs. It provides a flexible
means of manipulating data because it can adjust according to the size of the data.

32) In what data structures are pointers applied?

Pointers that are used in linked list have various applications in data structure. Data structures that make
use of this concept include the Stack, Queue, Linked List and Binary Tree.

33) Do all declaration statements result in a fixed reservation in memory?

Most declarations do, with the exemption of pointers. Pointer declaration does not allocate memory for
data, but for the address of the pointer variable. Actual memory allocation for the data comes during run-
time.

34) What are ARRAYs?

When dealing with arrays, data is stored and retrieved using an index that actually refers to the element
number in the data sequence. This means that data can be accessed in any order. In programming, an
array is declared as a variable having a number of indexed elements.

35) What is the minimum number of queues needed when implementing a priority queue?

The minimum number of queues needed in this case is two. One queue is intended for sorting priorities
while the other queue is intended for actual storage of data.

36) Which sorting algorithm is considered the fastest?

DEPT OF CSE,TOCE,2023-24 Page 75


DATA STRUCTURES LABORATORY (BCSL305)

There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort, merge sort,
etc. Not one can be considered the fastest because each algorithm is designed for a particular data
structure and data set. It would depend on the data set that you would want to sort.

37) Differentiate STACK from ARRAY.

Data that is stored in a stack follows a LIFO pattern. This means that data access follows a sequence
wherein the last data to be stored will the first one to be extracted. Arrays, on the other hand, does not
follow a particular order and instead can be accessed by referring to the indexed element within the array.

38) Give a basic algorithm for searching a binary search tree.

1. if the tree is empty, then the target is not in the tree, end search
2. if the tree is not empty, the target is in the tree
3. check if the target is in the root item
4. if target is not in the root item, check if target is smaller than the root’s value
5. if target is smaller than the root’s value, search the left subtree
6. else, search the right subtree

39) What is a dequeue?

A dequeue is a double-ended queue. This is a structure wherein elements can be inserted or removed from
either end.

40) What is a bubble sort and how do you perform it?

A bubble sort is one sorting technique that can be applied to data structures such as an array. It works by
comparing adjacent elements and exchanges their values if they are out of order. This method lets the
smaller values “bubble” to the top of the list, while the larger value sinks to the bottom.

41) What are the parts of a linked list?

A linked list typically has two parts: the head and the tail. Between the head and tail lie the actual nodes,
with each node being linked in a sequential manner.

42) How does selection sort work?

Selection sort works by picking the smallest number from the list and placing it at the front. This process
is repeated for the second position towards the end of the list. It is the simplest sort algorithm.

43) What is a graph?

A graph is one type of data structure that contains a set of ordered pairs. These ordered pairs are also
referred to as edges or arcs, and are used to connect nodes where data can be stored and retrieved.

DEPT OF CSE,TOCE,2023-24 Page 76


DATA STRUCTURES LABORATORY (BCSL305)

44) Differentiate linear from non linear data structure.

Linear data structure is a structure wherein data elements are adjacent to each other. Examples of linear
data structure include arrays, linked lists, stacks and queues. On the other hand, non-linear data structure
is a structure wherein each data element can connect to more than two adjacent data elements. Examples
of non linear data structure include trees and graphs.

45) What is an AVL tree?

An AVL tree is a type of binary search tree that is always in a state of partially balanced. The balance is
measured as a difference between the heights of the subtrees from the root. This self-balancing tree was
known to be the first data structure to be designed as such.

46) What are doubly linked lists?

Doubly linked lists are a special type of linked list wherein traversal across the data elements can be done
in both directions. This is made possible by having two links in every node, one that links to the next
node and other one that links to the previous node.

47) What is Huffman’s algorithm?

Huffman’s algorithm is associated in creating extended binary trees that has minimum weighted path
lengths from the given weights. It makes use of a table that contains frequency of occurrence for each
data element.

48) What is Fibonacci search?

Fibonacci search is a search algorithm that applies to a sorted array. It makes use of a divide-and-conquer
approach that can greatly reduce the time needed in order to reach the target element.

49) Briefly explain recursive algorithm.

Recursive algorithm targets a problem by dividing it into smaller, manageable sub-problems. The output
of one recursion after processing one sub-problem becomes the input to the next recursive process.

50) How do you search for a target key in a linked list?

To find the target key in a linked list, you have to apply sequential search. Each node is traversed and
compared with the target key, and if it is different, then it follows the link to the next node. This traversal
continues until either the target key is found or if the last node is reached.

DEPT OF CSE,TOCE,2023-24 Page 77


DATA STRUCTURES LABORATORY (BCSL305)

Textbooks:
1. Ellis Horowitz and Sartaj Sahni, Fundamentals of Data Structures in C, 2nd Ed, Universities Press,
2014.
2. Seymour Lipschutz, Data Structures Schaum's Outlines, Revised 1st Ed, McGraw Hill, 2014.

DEPT OF CSE,TOCE,2023-24 Page 78

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy