0% found this document useful (0 votes)
56 views72 pages

Data Structures Overview and C Program

Uploaded by

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

Data Structures Overview and C Program

Uploaded by

Maadhu Avati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DATA STRUCTURES LABORATORY (BCSL305)

DATA STRUCTURES
Data Structures:
The logical or mathematical model of a particular organization of data is called
data structures. Data structures is the study of logical relationship existing between
individual data elements, the way the data is organized in the memory and the efficient
way of storing, accessing and manipulating the data elements.
Choice of a particular data model depends on two considerations: it must be rich
enough in structure to mirror the actual relationships of the data in the real world. On
the other hand, the structure should be simple enough that one can effectively process
the data when necessary.
Data Structures can be classified as:
➢ Primitive data structures
➢ Non-Primitive data structures.
• Primitive data structures are the basic data structures that can be directly
manipulated/operated by machine instructions. Some of these are character,
integer, real, pointers etc.
• Non-primitive data structures are derived from primitive data structures, they
cannot be directly manipulated/operated by machine instructions, and these are
group of homogeneous or heterogeneous data items. Some of these are Arrays,
stacks, queues, trees, graphs etc.
Data structures are also classified as
➢ Linear data structures
➢ Non-Linear data structures.
In the Linear data structures processing of data items is possible in linear fashion, i.e.,
data can be processed one by one sequentially.
Example of such data structures are: Array, Linked list, Stacks, Queues
A data structure in which insertion and deletion is not possible in a linear fashion is
called as nonlinear data structure. i.e., which does not show the relationship of logical
adjacency between the elements is called as non-linear data structure. Such as trees,
graphs and files.
Data structure operations:
The particular data structures that one chooses for a given situation depends largely on

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 1


DATA STRUCTURES LABORATORY (BCSL305)

the frequency with which specific operations are performed. The following operations
play major role in the processing of data.
i) Traversing.
ii) Searching.
iii) Inserting.

iv) Deleting.
v) Sorting.
vi) Merging
STACKS:
A stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at the same end, called the TOP of the stack. A stack
is a non-primitive linear data structure. As all the insertion and deletion are done from
the same end, the first element inserted into the stack is the last element deleted from
the stack and the last element inserted into the stack is the first element to be deleted.
Therefore, the stack is called Last-In First-Out (LIFO) data structure.
QUEUES:
A queue is a non-primitive linear data structure. Where the operation on the queue is
based on First-In-First- Out FIFO process — the first element in the queue will be the
first one out. This is equivalent to the requirement that whenever an element is added,
all elements that were added before have to be removed before the new element can be
removed.
For inserting elements into the queue are done from the rear end and deletion is done
from the front end, we use external pointers called as rear and front to keep track of the
status of the queue. During insertion, Queue Overflow condition has to be checked.
Likewise during deletion, Queue Underflow condition is checked.
LINKED LIST:
Disadvantages of static/sequential allocation technique:
1) If an item has to be deleted then all the following items will have to be moved by
one allocation. Wastage of time.
2) Inefficient memory utilization.
3) If no consecutive memory (free) is available, execution is not possible.
Linear Linked Lists Types of Linked lists:
1) Single Linked lists
2) Circular Single Linked Lists

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 2


DATA STRUCTURES LABORATORY (BCSL305)

3) Double Linked Lists


4) Circular Double Linked Lists.
NODE:
Each node consists of two fields. Information (info) field and next address(next) field.
The info field consists of actual information/data/item that has to be stored in a list. The
second field next/link contains the address of the next node. Since next field contains
the address, It is of type pointer.Here the nodes in the list are logically adjacent to each
other. Nodes that are physically adjacent need not be logically adjacent in the list.
The entire linked list is accessed from an external pointer FIRST that points to (contains
the address of) the first node in the list. (By an “external” pointer, we mean, one that is
not included within a node. Rather its value can be accessed directly by referencing a
variable).
TREES:
Definition: A data structure which is accessed beginning at the root node. Each node is either
a leaf or an internal node. An internal node has one or more child nodes and is called the
parent of its child nodes. All children of the same node are siblings. Contrary to a physical
tree, the root is usually depicted at the top of the structure, and the leaves are depicted at the
bottom. A tree can also be defined as a connected, acyclic di-graph.

GRAPH:
Definition: A Graph G consists of two sets, V and E. V is a finite set of vertices. E is a set of
edges or pair of vertices.
Two types of graphs:
➢ Undirected Graph
➢ Directed Graph

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 3


DATA STRUCTURES LABORATORY (BCSL305)

Undirected Graph: In undirected graph the pair of vertices representing any edge is
unordered. Thus the pairs (u,v)and (v,u) represent the same edge.
Directed graph: In a directed graph each edge is represented by a directed pair , u is the tail
and v is the head of the edge. Therefore and represent two different edges.
Graph representation can be done using adjacency matrix.
➢ Adjacency matrix: Adjacency matrix is a two dimensional n x n array a, with the
property that a[i][j]=1 iff the edge (i,j) is in E(G). a[i][j]=0 if there is no such edge in
G.
➢ Connectivity of the graph: A graph is said to be connected iff for every pair of
distinct vertices u and v , there is a path from u to v.
➢ Path: A path from vertex u to v in a graph is a sequence of vertices u, i1 , i2 …… ik ,
v such that (u, i1), (i1 , i2) ……… (ik , v) are the edges in G.
Graph traversal can be done in two ways:
➢ depth first search(dfs) and
➢ breadth first search (bfs).
• Hashing: Hashing is a process of generating key or keys from a string of text using a
mathematical function called hash function. Hashing is a key-to-address mapping
process.
• Hash Table: In hashing the dictionary pairs are stored in a table called hash table.
Hash tables are partitioned into buckets, buckets consists of s slots , each slot is
capable of holding one dictionary pair.
• Hash function: A hash function maps a key into a bucket in the hash table. Most
commonly used hash function is,
h ( k ) = k % D where,
k is the key
D is Max size of hash table.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 4


DATA STRUCTURES LABORATORY (BCSL305)

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

Objective:
To revise the useful concept of programming prerequisite which will be useful for future lessons.
Structures, union, pointers, 1D array etc. are covered in this lab.
Brief Theory:
Structures: A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type. key word is used to create a
structure. Syntax of structure:
Struct strcture_name
{
datatype member1;
datatype member1;
...
datatype member1;
};
Problems on:
1. Basic C program using loops, structure.
2. Programs on unions, 1D array.
3. To design a small database type application using structure, pointer, array and dynamic memory
allocation.
Observations/Outcome:
1. Develop the understanding of data structure and its types.
2. Ability to use various data structures for solving unseen problems.
3. Understand the use of appropriate data structure to solve real world problems.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 5


DATA STRUCTURES LABORATORY (BCSL305)

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

// Structure to represent a day in the calendar


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

// Function to create a day


void create(struct Day * day)
{
// Allocate memory for the day name and activity
day -> dayName = (char * ) malloc(sizeof(char) * 20);
day -> activity = (char * ) malloc(sizeof(char) * 100);
// Input the day details
printf("Enter the day name:");
scanf("%s", day -> dayName);
printf("Enter the date:");
scanf("%d", & day -> date);
printf("Enter the activity for the day:");
scanf(" %[^\n]s", day -> activity);
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 6


DATA STRUCTURES LABORATORY (BCSL305)

// Function to read data from the keyboard and create the calendar
void read(struct Day * calendar, int size)
{
for (int i = 0; i < size; i++)
{
printf("Enter details for Day %d:\n", i + 1);
create( & calendar[i]);
}
}
// Function to display the calendar
void display(struct Day * calendar, int size)
{
printf("\nWeek's Activity Details:\n");
for (int i = 0; i < size; i++)
{
printf("Day %d:\n", i + 1);
printf("Day Name: %s\n", calendar[i].dayName);
printf("Date: %d\n", calendar[i].date);
printf("Activity: %s\n", calendar[i].activity);
printf("\n");
}
}

// Function to free the dynamically allocated memory


void freeMemory(struct Day * calendar, int size)
{
for (int i = 0; i < size; i++)
{
free(calendar[i].dayName);
free(calendar[i].activity);

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 7


DATA STRUCTURES LABORATORY (BCSL305)

}
}
int main()
{
int size;
printf("Enter the number of days in the week:");
scanf("%d", & size);

// Dynamically allocate memory for the calendar


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

// Check if memory allocation is successful


if (calendar == NULL)
{
printf("Memory allocation failed. Exiting program.\n");
return 1;
}
// Read and display the calendar
read(calendar, size);
display(calendar, size);

// Free the dynamically allocated memory


freeMemory(calendar, size);

// Free the memory allocated for the calendar array


free(calendar);

return 0;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 8


DATA STRUCTURES LABORATORY (BCSL305)

OUTPUT:
Enter the number of days in the week: 7
Enter details for Day 1:
Enter the day name: Sunday
Enter the date: 1
Enter the activity for the day: Learning
Enter details for Day 2:
Enter the day name: Monday
Enter the date: 2
Enter the activity for the day: Coding
Enter details for Day 3:
Enter the day name: Tuesday
Enter the date: 3
Enter the activity for the day: Testing
Enter details for Day 4:
Enter the day name: Wednesday
Enter the date: 4
Enter the activity for the day: Debugging
Enter details for Day 5:
Enter the day name: Thrusday
Enter the date: 5
Enter the activity for the day: Publishing
Enter details for Day 6:
Enter the day name: Friday
Enter the date: 6
Enter the activity for the day: Marketing
Enter details for Day 7:
Enter the day name: Saturday
Enter the date: 7
Enter the activity for the day: Earning

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 9


DATA STRUCTURES LABORATORY (BCSL305)

Week's Activity Details:


Day 1:
Day Name: Sunday
Date: 1
Activity: Learning
Day 2:
Day Name: Monday
Date: 2
Activity: Coding
Day 3:
Day Name: Tuesday
Date: 3
Activity: Testing
Day 4:
Day Name: Wednesday
Date: 4
Activity: Debugging
Day 5:
Day Name: Thrusday
Date: 5
Activity: Publishing
Day 6:
Day Name: Friday
Date: 6
Activity: Marketing
Day 7:
Day Name: Saturday
Date: 7
Activity: Earning

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 10


DATA STRUCTURES LABORATORY (BCSL305)

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

Objectives:
To revise the useful concept of programming prerequisite which will be useful for future lessons.
Strings and operations on strings are are covered in this lab.

Brief 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. The
following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than
the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
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 s1s2.
• 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.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 11


DATA STRUCTURES LABORATORY (BCSL305)

Problems on:
1. Basic C program using strings
2. Programs on string, pattern match

Observations/Outcome:
1. Develop the understanding of strings and operations on strings.
2. Understand the use of appropriate data structure to solve real world problems.

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.

SOURCE CODE:
#include<stdio.h>
char str[50], pat[20], rep[20], res[50];
int c = 0, m = 0, i = 0, j = 0, k, flag = 0;
void stringmatch()
{
while (str[c] != '\0')
{
if (str[m] == pat[i])
{
i++;
m++;
if (pat[i] == '\0')
{
flag = 1;
for (k = 0; rep[k] != '\0'; k++, j++)
{

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 12


DATA STRUCTURES LABORATORY (BCSL305)

res[j] = rep[k];
}
i = 0;
c = m;
}
}
else
{
res[j] = str[c];
j++;
c++;
m = c;
i = 0;
}
}
res[j] = '\0';
}

void main()
{
printf("Enter the main string:");
gets(str);
printf("\nEnter the pat string:");
gets(pat);
printf("\nEnter the replace string:");
gets(rep);
printf("\nThe string before pattern match is:\n %s", str);
stringmatch();
if (flag == 1)
printf("\nThe string after pattern match and replace is: \n %s ", res);
else
printf("\nPattern string is not found");

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 13


DATA STRUCTURES LABORATORY (BCSL305)

}
OUTPUT1:
Enter the main string:Designed by vtucode
Enter the pat string:vtucode
Enter the replace string:Braham

The string before pattern match is:


Designed by vtucode

The string after pattern match and replace is:


Designed by Braham

OUTPUT2:
Enter the main string:Designed by Developer
Enter the pat string:vtucode
Enter the replace string:Braham

The string before pattern match is:


Designed by Developer
Pattern string is not found

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 14


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.

Objectives:
Learn about Stack, stack oprations are covered in this lab.

Brief Theory:
A stack is an abstract data type (ADT), commonly used in most programming languages. It is named
stack as it behaves like a real-world stack.
A real-world stack allows operations at one end only. For example, we can place or remove a card or
plate from top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At
any given time, we can only access the top element of a stack. This feature makes it LIFO data
structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last
is accessed first. In stack terminology, insertion operation is called PUSH operation and removal
operation is called POP operation.
Basic Operations:
• 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.

Problems on:
1. Basic C program using stacks
2. Palindrome function implementation using stack.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 15


DATA STRUCTURES LABORATORY (BCSL305)

Observations/Outcome:
1. Develop the understanding of stack operations
2. Understand the use of appropriate data structure to solve real world problems.

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 4: Pop element from stack along with display the stack contents. if stack is empty give a message
as „Stack is Underflow‟.
Step 5: Check whether the stack contents are Palindrome or not.
Step 6: Stop.

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
#define MAX 3 //you can change this size according to your requirement
int s[MAX];
int top = -1;
void push(int item);
int pop();
void palindrome();
void display();

void main()
{
int choice, item;
while (1)
{
printf("\n\n\n\n~~~~~~Menu~~~~~~ : ");
printf("\n=>1.Push an Element to Stack and Overflow demo ");
printf("\n=>2.Pop an Element from Stack and Underflow demo");
printf("\n=>3.Palindrome demo ");

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 16


DATA STRUCTURES LABORATORY (BCSL305)

printf("\n=>4.Display ");
printf("\n=>5.Exit");
printf("\nEnter your choice: ");
scanf("%d", & choice);
switch (choice)
{
case 1:
printf("\nEnter an element to be pushed: ");
scanf("%d", & item);
push(item);
break;

case 2:
item = pop();
if (item != -1)
printf("\nElement popped is: %d", item);
break;

case 3:
palindrome();
break;

case 4:
display();
break;

case 5:
exit(1);

default:
printf("\nPlease enter valid choice ");
break;

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 17


DATA STRUCTURES LABORATORY (BCSL305)

}
}
}

void push(int item)


{
if (top == MAX - 1)
{
printf("\n~~~~Stack overflow~~~~");
return;
}
top = top + 1;
s[top] = item;
}

int pop()
{
int item;
if (top == -1)
{
printf("\n~~~~Stack underflow~~~~");
return -1;
}
item = s[top];
top = top - 1;
return item;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 18


DATA STRUCTURES LABORATORY (BCSL305)

void display()
{
int i;
if (top == -1)
{
printf("\n~~~~Stack is empty~~~~");
return;
}
printf("\nStack elements are:\n ");
for (i = top; i >= 0; i--)
printf("| %d |\n", s[i]);
}

void palindrome()
{
int flag = 1, i;
printf("\nStack content are:\n");
for (i = top; i >= 0; i--)
printf("| %d |\n", s[i]);printf("\nReverse of stack content are:\n");
for (i = 0; i <= top; i++)
printf("| %d |\n", s[i]);
for (i = 0; i <= top / 2; i++)
{
if (s[i] != s[top - i])
{
flag = 0;
break;
}
}
if (flag == 1)
{

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 19


DATA STRUCTURES LABORATORY (BCSL305)

printf("\nIt is palindrome number");


}
Else
{
printf("\nIt is not a palindrome number");
}
}

OUTPUT:
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11

~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 12

~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 20


DATA STRUCTURES LABORATORY (BCSL305)

=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 13
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 14
~~~~Stack overflow~~~~

~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 13 |
| 12 |
| 11 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 13

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 21


DATA STRUCTURES LABORATORY (BCSL305)

~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 12 |
| 11 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 12
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 11
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 22


DATA STRUCTURES LABORATORY (BCSL305)

Enter your choice: 2


~~~~Stack underflow~~~~
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
~~~~Stack is empty~~~~
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 22
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 23


DATA STRUCTURES LABORATORY (BCSL305)

Enter your choice: 1


Enter an element to be pushed: 11
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 3
Stack content are:
| 11 |
| 22 |
| 11 |
Reverse of stack content are:
| 11 |
| 22 |
| 11 |
It is palindrome number
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 11
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 24


DATA STRUCTURES LABORATORY (BCSL305)

Enter your choice: 2


Element popped is: 22
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 33
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 22
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 3
Stack content are:
| 22 |
| 33 |
| 11 |
Reverse of stack content are:
| 11 |
| 33 |

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 25


DATA STRUCTURES LABORATORY (BCSL305)

| 22 |It is not a palindrome number


~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 5

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 26


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.

ABOUT THE EXPERIMENT:


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+ Examples of Infix, Prefix, and Postfix

Infix Expression Prefix Expression Postfix Expression


A+B +AB AB+
A+B*C +A*BC ABC*+

ALGORITHM:
Step 1: Start.
Step 2: Read an infix expression with parenthesis and without parenthesis.
Step 3: convert the infix expression to postfix expression. Step 4: Stop

SOURCE CODE
#include<stdio.h>
void infix_to_postfix();
void push(char);
char pop();
int priority(char);
char infix[30], postfix[30],stack[30];
int top=-1;

void main()
{
printf("Enter the valid Infix expression \n");
scanf("%s",infix);
infix_to_postfix();
printf("\n Infix expression : %s",infix);
printf("\n Postfix expression : %s\n",postfix);
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 27


DATA STRUCTURES LABORATORY (BCSL305)

// push symbol to stack


void push(char item)
{
stack[++top]=item;
} // end of function push

// pop symbol from stack


char pop()
{
return stack[top--];
} // end of function pop

// check the priority of operator


int priority(char symb)
{
int p;
switch(symb)
{
case '+':
case '-': p=1;
break;
case '*':
case '/':
case '%': p=2;
break;
case '^':
case '$': p=3;
break;
case '(':
case ')': p=0;
break;
case '#': p=-1;
break;
} // end of switch
return p;
} // end of function priority

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 28


DATA STRUCTURES LABORATORY (BCSL305)

//converting an Infix Expression to Postfix Expression


void infix_to_postfix()
{
int i=0,j=0;
char symb,temp;
push('#');
for(i=0;infix[i]!='\0';i++)
{
symb=infix[i];
switch(symb)
{
case '(': push(symb); // push all symbols
inside the ( to top of stack
break;
case ')': temp=pop(); //pop symbol from top
of stack
while(temp!='(') //pop all symbols from
top of stack and store in postfix until (
{
postfix[j++]=temp;
temp=pop();
} // end of while
break;
case'+':
case'-':
case'*':
case'/':
case'%':
case'^':
case'$':
while(priority(stack[top])>=priority(symb)) // check for
priority of operator
{
temp=pop();
postfix[j++]=temp;
}
push(symb);
break;
default: postfix[j++]=symb;
} // end of switch
} // end of for
while(top>0) // pop remaining all symbols form
top of stack and store to postfix
{
temp=pop();
postfix[j++]=temp;
} // end of while
postfix[j]='\0'; // end string postfix
} // end of function infix_to_postfix

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 29


DATA STRUCTURES LABORATORY (BCSL305)

OUTPUT:
Sample Output 1
Enter the valid Infix expression
(a+b)*c/d^5%1
Infix expression: (a+b)*c/d^5%1
Postfix expression: ab+c*d5^/1%

Sample Output 2
Enter the valid Infix expression
(a+(b-c)*d)
Infix expression: (a+(b-c)*d)
Postfix expression: abc-d*+

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 30


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

ABOUT THE EXPERIMENT:


a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
Postfix/Suffix Expression: Operators are written after their operands.
Ex: XY+ In normal algebra we use the infix notation like a+b*c. The corresponding postfix
notation is abc*+.
Example: Postfix String: 123*+4- Initially the Stack is empty. Now, the first three characters
scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that
order.

Next character scanned is "*", which is an operator. Thus, we pop the top two elements from
the stack and perform the "*" operation with the two operands. The second operand will be
the first element that is popped.

The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.

Next character scanned is "+", which is an operator. Thus, we pop the top two elements from
the stack and perform the "+" operation with the two operands. The second operand will be
the first element that is popped.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 31


DATA STRUCTURES LABORATORY (BCSL305)

The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.

Next character scanned is "4", which is added to the stack.

Next character scanned is "-", which is an operator. Thus, we pop the top two elements from
the stack and perform the "-" operation with the two operands. The second operand will be the
first element that is popped.

The value of the expression (7-4) that has been evaluated(3) is pushed into the stack. Now,
since all the characters are scanned, the remaining element in the stack (there will be only one
element in the stack) will be returned. End result: Postfix String:123*+4- Result: 3

B) Towers of Hanoi Solving Tower of Hanoi problem with n disks.


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

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 32


DATA STRUCTURES LABORATORY (BCSL305)

2 n - 1, where n is the number of disks.

ALGORITHM:
Step 1: Start.
Step 2: Read N number of discs.
Step 3: Move all the discs from source to destination by using temp rod.
Step 4: Stop.
#include<stdio.h>
#include<math.h>
void push(float);
float pop();
void evaluate(char[]);
float stack[20];
int top=-1;

void main()
{
int choice,n;
char postfix[100];
while(1) // infinate loop for menu
{
printf("\n STACK APPLICATIONS");
printf("\n Enter your Choice: ");
printf("\n 1. Evaluation of postfix expression with
single digit operands and operators");
printf("\n 2. Solving Tower of Hanoi problem with N
disks");
printf("\n 3. Exit \n");
scanf("%d", &choice);
switch(choice)
{
case 1 : printf("Enter a valid postfix
expression\n");
scanf("%s",postfix);
evaluate(postfix);
break;
case 2 : printf("\n Enter the number of
discs:\n");
scanf("%d",&n);
tower(n,'A','C','B');

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 33


DATA STRUCTURES LABORATORY (BCSL305)

printf("\n Total number of moves are


%d",(int)pow(2,n)-1);
break;
case 3 : return;
default : printf("\n Invalid Choice");
} // end of switch
} // end of menu
} // end of main

// push item to stack


void push(float item)
{
stack[++top]=item;
} // end of push

// pop item from stack


float pop()
{
return stack[top--];
} // end of pop

// function to postfix expression with single digit operands


and operators: +, -, *, /, %, ^
void evaluate(char postfix[100])
{
int i;
float op1, op2, res;
char symb;
for(i=0;postfix[i]!='\0';i++) // repeate until end of
string
{
symb=postfix[i];
if(isdigit(symb)) // check for digit or not
push(symb-'0'); // if digit push to top of
stack -'0' is for ascii to number conversion
switch(symb)
{
case '+':op2=pop();
op1=pop();
res=op1+op2;
push(res);
break;
case '-':op2=pop();
op1=pop();
res=op1-op2;
push(res);
break;
case '*':op2=pop();
op1=pop();
res=op1*op2;
push(res);

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 34


DATA STRUCTURES LABORATORY (BCSL305)

break;
case '/':op2=pop();
op1=pop();
if(op2==0)
{
printf("Division by zero
Error\n");
return;
}
res=op1/op2;
push(res);
break;
case '%': op2=pop();
op1=pop();
if(op2==0)
{
printf("Division by zero
Error\n");
return;
}
res=(int)op1%(int)op2; // typecast
operands to int because % supports only int operands
push(res);
break;
case '^':op2=pop();
op1=pop();
res=pow(op1,op2);
push(res);
break;
}// end of switch
} // end of for
res=pop(); // pop the final answer from top of stack
if(top==-1) // Check for empty stack, If true then its
valid postfix expression
printf("\n Result: %f\n ",res); // Display the final
answer
else
{ //otherwise invalid postfix expression
printf("\nINVALID POSTFIX EXPRESSION\n");
top=-1; //reset top to -1
}

} // end of evaluate function

// Recursive function for Solving Tower of Hanoi problem with


N disks
void tower(int n,int source,int destination,int aux)
{
if(n==0)
return;
tower(n-1,source,aux,destination);

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 35


DATA STRUCTURES LABORATORY (BCSL305)

printf("\n Move disc %d from %c to


%c",n,source,destination);
tower(n-1,aux,destination,source);
} // end of tower function

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 36


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

ABOUT THE EXPERIMENT:


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. Circular linked list fallow the First
In First Out principle. 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. Any position before front is also after rear.

Observations/Outcome:
1. Better understanding of different types of queues.
2. To understand efficient approaches to implement queue using arrays and linked lists.
Problems on:
1. Creation of Queue using array and then implementation of and operations.
2. Problems on circular queue of array implementation.
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.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 37


DATA STRUCTURES LABORATORY (BCSL305)

Source code
#include <stdio.h>
#include <stdlib.h>
#define max 5
int q[max],f=-1,r=-1;
void ins()
{
if(f==(r+1)%max)
printf("\nQueue overflow");
else
{
if(f==-1)
f++;
r=(r+1)%max;
printf("\nEnter element to be inserted:");
scanf("%d",&q[r]);
}
}
void del()
{
if(r==-1)
printf("\nQueue underflow");
else
{
printf("\nElemnt deleted is:%d",q[f]);
if(f==r)
f=r=-1;
else
f=(f+1)%max;
}
}
void disp()
{
if(f==-1)
printf("\nQueue empty");
else
{
int i;
printf("\nQueue elements are:\n");
for(i=f;i!=r;i=(i+1)%max)
printf("%d\t",q[i]);
printf("%d",q[i]);
printf("\nFront is at:%d\nRear is at:%d",q[f],q[r]);
}
}
int main()
{
printf("\nCircular Queue operations");
printf("\n1.Insert");
printf("\n2.Delete");

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 38


DATA STRUCTURES LABORATORY (BCSL305)

printf("\n3.Display");
printf("\n4.Exit");
int ch;
do{
printf("\nEnter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:ins();break;
case 2:del();break;
case 3:disp();break;
case 4:exit(0);
default:printf("\nInvalid choice...!");
}
}while(1);
return 0;

OUTPUT:

SAMPLE OUTPUT 2:
Circular Queue operations
1.insert
2.delete
3.display
4.exit
Enter your choice:1
Enter element to be insert:1000
Enter your choice:1
Enter element to be insert:2000
Enter your choice:1
Enter element to be insert:3000
Enter your choice:3
1000 2000 3000 rear is at 3000 front is at 1000
Enter your choice:2
Deleted element is:1000
Enter your choice:3 2000 3000 rear is at 3000 front is at 2000
Enter your choice:4
Exit

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 39


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

ABOUT THE EXPERIMENT: Linked List is a linear data structure and it is very common
data structure which consists of group of nodes in a sequence which is divided in two parts.
Each node consists of its own data and the address of the next node and forms a chain.
Linked Lists are used to create trees and graphs.
• They are a dynamic in nature which allocates the memory when required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.
• Linked lists are used to implement stacks, queues, graphs, etc.
• Linked lists let you insert elements at the beginning and end of the list.
• In Linked Lists we don t need to know the size in advance.

Observations/Outcomes:
1. To get an idea of Linked List and its types.
2. The students will be able to develop Linked List and its type from scratch.
Problems on:
1. Problem on implementation of the various operations on singly Linked List, like
create, display, delete.
2. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 40


DATA STRUCTURES LABORATORY (BCSL305)

ALGORITHM:
Step 1: Start.
Step 2: Read the value of N. (N student s information) ‟
Step 3: Create a singly linked list. (SLL)
Step 4: Display the status of SLL.
Step 5: Count the number of nodes.
Step 6: Perform insertion at front of list.
Step 7: Perform deletion at the front of the list.
Step 8: Perform insertion at end of the list.
Step 9: Perform deletion at the end of the list.
Step 10: Demonstrate how singly linked list can be used as stack.
Step 11: Demonstrate how singly linked list can be used as queue.
Step 12: Stop.

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
struct node

char usn[25], name[25], branch[25];


int sem;
long int phone;
struct node * link;
};
typedef struct node * NODE;
NODE start = NULL;
int count = 0;

NODE create()
{
NODE snode;
snode = (NODE) malloc(sizeof(struct node));
if (snode == NULL)
{
printf("\nMemory is not available");
exit(1);
}
printf("\nEnter the usn,Name,Branch, sem,PhoneNo of the
student:");
scanf("%s %s %s %d %ld", snode -> usn, snode -> name,
snode -> branch, & snode -> sem, & snode -> phone);
snode -> link = NULL;
count++;

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 41


DATA STRUCTURES LABORATORY (BCSL305)

return snode;
}

NODE insertfront()
{
NODE temp;
temp = create();
if (start == NULL)
{
return temp;
}
temp -> link = start;
return temp;
}

NODE deletefront()
{
NODE temp;
if (start == NULL)
{
printf("\nLinked list is empty");
return NULL;
}
if (start -> link == NULL)
{
printf("\nThe Student node with usn:%s is deleted ",
start -> usn);
count--;
free(start);
return NULL;
}
temp = start;
start = start -> link;
printf("\nThe Student node with usn:%s is deleted",
temp -> usn);
count--;
free(temp);
return start;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 42


DATA STRUCTURES LABORATORY (BCSL305)

NODE insertend()
{
NODE cur, temp;
temp = create();
if (start == NULL)
{
return temp;
}
cur = start;
while (cur -> link != NULL)
{
cur = cur -> link;
}
cur -> link = temp;
return start;
}

NODE deleteend()
{
NODE cur, prev;
if (start == NULL)
{
printf("\nLinked List is empty");
return NULL;
}
if (start -> link == NULL)
{
printf("\nThe student node with the usn:%s is
deleted",start -> usn);
free(start);
count--;
return NULL;
}
prev = NULL;
cur = start;
while (cur -> link != NULL)
{
prev = cur;
cur = cur -> link;
}
printf("\nThe student node with the usn:%s is deleted",
cur -> usn);
free(cur);
prev -> link = NULL;
count--;
return start;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 43


DATA STRUCTURES LABORATORY (BCSL305)

void display()
{
NODE cur;
int num = 1;
if (start == NULL)
{
printf("\nNo Contents to display in SLL \n");
return;

}
printf("\nThe contents of SLL: \n");
cur = start;
while (cur != NULL)
{
printf("\n||%d|| USN:%s| Name:%s| Branch:%s| Sem:%d|
Ph:%ld|", num, cur -> usn, cur -> name, cur ->
branch, cur -> sem, cur -> phone);
cur = cur -> link;
num++;
}
printf("\n No of student nodes is %d \n", count);
}

void stackdemo()
{
int ch;
while (1) {
printf("\n~~~Stack Demo using SLL~~~\n");
printf("\n1:Push operation \n2: Pop operation \n3:
Display \n4:Exit \n");
printf("\nEnter your choice for stack demo:");
scanf("%d", & ch);
switch (ch)
{
case 1:
start = insertfront();
break;

case 2:
start = deletefront();
break;

case 3:
display();
break;
default:
return;
}
}
return;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 44


DATA STRUCTURES LABORATORY (BCSL305)

int main()
{
int ch, i, n;
while (1)
{
printf("\n~~~Menu~~~");
printf("\nEnter your choice for SLL operation \n");
printf("\n1:Create SLL of Student Nodes");
printf("\n2:DisplayStatus");
printf("\n3:InsertAtEnd");
printf("\n4:DeleteAtEnd");
printf("\n5:Stack Demo using SLL(Insertion and
Deletion at Front)");
printf("\n6:Exit \n");
printf("\nEnter your choice:");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nEnter the no of students: ");
scanf("%d", & n);
for (i = 1; i <= n; i++)
start = insertfront();
break;
case 2:
display();
break;
case 3:
start = insertend();
break;
case 4:
start = deleteend();
break;
case 5:
stackdemo();
break;
case 6:
exit(0);
default:
printf("\nPlease enter the valid choice");}
}
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 45


DATA STRUCTURES LABORATORY (BCSL305)

OUTPUT:
~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:1Enter the no of students: 3
Enter the usn,Name,Branch, sem,PhoneNo of the student:
1ME21CS017
Braham
CSE
5
8768586443Enter the usn,Name,Branch, sem,PhoneNo of the
student:
1ME21CS015
Bikash
CSE
5
8734687996Enter the usn,Name,Branch, sem,PhoneNo of the
student:
1ME21AI015
Shoaib
AI&ML
5
6748353877~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:2
The contents of SLL:||1|| USN:1ME21AI015| Name:Shoaib|
Branch:AI&ML| Sem:5| Ph:6748353877|
||2|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
||3|| USN:1ME21CS017| Name:Braham| Branch:CSE| Sem:5|
Ph:8768586443|
No of student nodes is 3~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:3Enter the usn,Name,Branch,
sem,PhoneNo of the student:
1ME21CS068
Rajan

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 46


DATA STRUCTURES LABORATORY (BCSL305)

CSE
5
3426527765~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:2
The contents of SLL:||1|| USN:1ME21AI015| Name:Shoaib|
Branch:AI&ML| Sem:5| Ph:6748353877|
||2|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
||3|| USN:1ME21CS017| Name:Braham| Branch:CSE| Sem:5|
Ph:8768586443|
||4|| USN:1ME21CS068| Name:Rajan| Branch:CSE| Sem:5|
Ph:3426527765|
No of student nodes is 4~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:4
The student node with the usn:1ME21CS068 is deleted~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:2
The contents of SLL:||1|| USN:1ME21AI015| Name:Shoaib|
Branch:AI&ML| Sem:5| Ph:6748353877|
||2|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
||3|| USN:1ME21CS017| Name:Braham| Branch:CSE| Sem:5|
Ph:8768586443|
No of student nodes is 3~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:4
The student node with the usn:1ME21CS017 is deleted~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 47


DATA STRUCTURES LABORATORY (BCSL305)

2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:5
~~~Stack Demo using SLL~~~1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:1Enter the
usn,Name,Branch, sem,PhoneNo of the student:
1ME21CS005
Aman
CSE
5
6587594335~~~Stack Demo using SLL~~~1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:3
The contents of SLL:||1|| USN:1ME21CS005| Name:Aman|
Branch:CSE| Sem:5| Ph:6587594335|
||2|| USN:1ME21AI015| Name:Shoaib| Branch:AI&ML| Sem:5|
Ph:6748353877|
||3|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
No of student nodes is 3~~~Stack Demo using SLL~~~1: Push
operation
2: Pop operation
3: Display
4: ExitEnter your choice for stack demo:1Enter the
usn,Name,Branch, sem,PhoneNo of the student:
1ME21CS092
Shubham
CSE
5
9869754354~~~Stack Demo using SLL~~~
1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:3
The contents of SLL:||1|| USN:1ME21CS092| Name:Shubham|
Branch:CSE| Sem:5| Ph:9869754354|
||2|| USN:1ME21CS005| Name:Aman| Branch:CSE| Sem:5|
Ph:6587594335|
||3|| USN:1ME21AI015| Name:Shoaib| Branch:AI&ML| Sem:5|
Ph:6748353877|
||4|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
No of student nodes is 4~~~Stack Demo using SLL~~~1:Push
operation
2: Pop operation
3: Display

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 48


DATA STRUCTURES LABORATORY (BCSL305)

4:ExitEnter your choice for stack demo:2


The Student node with usn:1ME21CS092 is deleted~~~Stack Demo
using SLL~~~1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:3
The contents of SLL:||1|| USN:1ME21CS005| Name:Aman|
Branch:CSE| Sem:5| Ph:6587594335|
||2|| USN:1ME21AI015| Name:Shoaib| Branch:AI&ML| Sem:5|
Ph:6748353877|
||3|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
No of student nodes is 3~~~Stack Demo using SLL~~~1: Push
operation
2: Pop operation
3: Display
4: ExitEnter your choice for stack demo:4~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:6

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 49


DATA STRUCTURES LABORATORY (BCSL305)

PROGRAM 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

Problems on:
1. Problem on implementation of the various operations on Linked List, like create, display,
delete.
2. Program to create doubly linked list, and Count no of nodes.
3. Inserting, deleting elements in linked list at various position.
Observations/Outcomes:
1. To get an idea of Linked List and its types.
2. The students will be able to develop Linked List and its type from scratch

ALGORITHM:
Step 1: Start.
Step 2: Read the value of N. (N student s information) ‟
Step 3: Create a doubly linked list. (DLL)
Step 4: Display the status of DLL.
Step 5: Count the number of nodes.
Step 6: Perform insertion at front of list.
Step 7: Perform deletion at the front of the list.
Step 8: Perform insertion at end of the list.
Step 9: Perform deletion at the end of the list.
Step 10: Demonstrate how doubly linked list can be used as double ended queue.
Step 11: Stop.

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 50


DATA STRUCTURES LABORATORY (BCSL305)

SOURCE CODE
#include<stdio.h>
#include<stdlib.h>
struct node
{
char ssn[25], name[25], dept[10], designation[25];
int sal;
long int phone;
struct node * llink;
struct node * rlink;
};
typedef struct node * NODE;
NODE first = NULL;
int count = 0;NODE

create()
{
NODE enode;
enode = (NODE) malloc(sizeof(struct node));
if (enode == NULL)
{
printf("\nRunning out of memory");
exit(0);
}
printf("\nEnter the ssn, Name, Department,
Designation, Salary, PhoneNo of the
employee:\n");
scanf("%s %s %s %s %d %ld", enode -> ssn, enode -> name,
enode -> dept, enode -> designation, & enode ->
sal, & enode -> phone);
enode -> llink = NULL;
enode -> rlink = NULL;
count++;
return enode;
}

NODE insertfront()
{
NODE temp;
temp = create();
if (first == NULL)
{
return temp;
}
temp -> rlink = first;
first -> llink = temp;
return temp;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 51


DATA STRUCTURES LABORATORY (BCSL305)

void display()
{
NODE cur;
int nodeno = 1;
cur = first;
if (cur == NULL)
printf("\nNo Contents to display in DLL");
while (cur != NULL)
{
printf("\nENode:%d||SSN:%s|Name:%s|Department:%s|
Designation:%s|Salary:%d|Phone no:%ld", nodeno,
cur -> ssn, cur -> name, cur -> dept, cur ->
designation, cur -> sal, cur -> phone);
cur = cur -> rlink;
nodeno++;
}
printf("\nNo of employee nodes is %d", count);
}

NODE deletefront()
{
NODE temp;
if (first == NULL)
{
printf("\nDoubly Linked List is empty");
return NULL;
}
if (first -> rlink == NULL)
{
printf("\nThe employee node with the ssn:%s
is deleted", first -> ssn);
free(first);
count--;
return NULL;
}
temp = first;
first = first -> rlink;
temp -> rlink = NULL;
first -> llink = NULL;
printf("\nThe employee node with the ssn:%s
is deleted", temp -> ssn);
free(temp);
count--;
return first;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 52


DATA STRUCTURES LABORATORY (BCSL305)

NODE insertend()
{
NODE cur, temp;
temp = create();
if (first == NULL)
{
return temp;
}
cur = first;
while (cur -> rlink != NULL)
{
cur = cur -> rlink;
}
cur -> rlink = temp;
temp -> llink = cur;
return first;
}

NODE deleteend()
{
NODE prev, cur;
if (first == NULL)
{
printf("\nDoubly Linked List is empty");
return NULL;
}
if (first -> rlink == NULL)
{
printf("\nThe employee node with the ssn:%s
is deleted", first -> ssn);
free(first);
count--;
return NULL;
}
prev = NULL;
cur = first;
while (cur -> rlink != NULL)
{
prev = cur;
cur = cur -> rlink;
}
cur -> llink = NULL;
printf("\nThe employee node with the ssn:%s
is deleted", cur -> ssn);
free(cur);
prev -> rlink = NULL;
count--;
return first;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 53


DATA STRUCTURES LABORATORY (BCSL305)

void deqdemo()
{
int ch;
while (1)
{
printf("\nDemo Double Ended Queue Operation");
printf("\n1:InsertQueueFront\n 2: DeleteQueueFront\n
3:InsertQueueRear\n 4:DeleteQueueRear\n
5:DisplayStatus\n 6: Exit \n");
scanf("%d", & ch);
switch (ch)
{
case 1:
first = insertfront();
break;
case 2:
first = deletefront();
break;
case 3:
first = insertend();
break;
case 4:
first = deleteend();
break;
case 5:
display();
break;
default:
return;
}
}
}

void main()
{
int ch, i, n;
while (1)
{
printf("\n\n~~~Menu~~~");
printf("\n1:Create DLL of Employee Nodes");
printf("\n2:DisplayStatus");
printf("\n3:InsertAtEnd");
printf("\n4:DeleteAtEnd");
printf("\n5:InsertAtFront");
printf("\n6:DeleteAtFront");
printf("\n7:Double Ended Queue Demo using DLL");
printf("\n8:Exit \n");
printf("\nPlease enter your choice: ");
scanf("%d", & ch);
switch (ch)
{

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 54


DATA STRUCTURES LABORATORY (BCSL305)

case 1:
printf("\nEnter the no of Employees: ");
scanf("%d", & n);
for (i = 1; i <= n; i++)
first = insertend();
break;
case 2:
display();
break;
case 3:
first = insertend();
break;
case 4:
first = deleteend();
break;
case 5:
first = insertfront();
break;
case 6:
first = deletefront();
break;
case 7:
deqdemo();
break;
case 8:
exit(0);
default:
printf("\nPlease Enter the valid choice");
}
}
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 55


DATA STRUCTURES LABORATORY (BCSL305)

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) = 6x 2 y 2 z-4yz 5 +3x 3 yz+2xy 5 z-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

SOURCE CODE:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct
node1
{
int coef, po_x,po_y,po_z;
struct node1 *next;
};
typedef struct node1* node;

node insert(node head,int coef,int po_x, int po_y, int po_z)


{
node p,q;
p=(node)malloc(size
of(struct node1));
p->coef=coef;
p-
>po_x=po_
x;
p-
>po_y=po_
y;
p-
>po_z=po_
z;
p-
>next=NUL
L;

q= head;

while(q-
>next!=head
) q=q->next;

q->next=p;
p->next=head;

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 56


DATA STRUCTURES LABORATORY (BCSL305)

return head;
}
void display(node head)
{

if(head->next==head)
{
printf("Polynomial is enmpty");
return;
}
node cur;
cur=head-
>next; do
{
printf("%dx^ %dy^%dz^%d",cur->coef,cur-
>po_x,cur->po_y,cur->po_z); cur=cur-
>next;
if(cur!=head)
{
printf(" + ");
}
}while(cur!=h
ead);
printf("\n");
}
int eval(node head, int x, int y , int z)
{
int ans=0, term;
if(head->next==head)
{
return ans;
}

node cur= head->next;


do
{
term=cur->coef;
term *=
pow(x,cur-
>po_x); term *=
pow(y,cur-
>po_y); term *=
pow(z,cur-
>po_z);
ans+=term;
cur=cur->next;
}while(cur!=head);

return ans;
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 57


DATA STRUCTURES LABORATORY (BCSL305)

bool match(node p1, node p2)


{
bool flag=true;
if(p1->po_x!=p2->po_x)
flag=false;
if(p1->po_y!=p2->po_y)
flag=false;
if(p1->po_z!=p2->po_z)
flag=false;
return flag;
}

node add(node p1,node p2, node res)


{
node
cur1,
cur2;
cur1=p1-
>next;
cur2=p2-
>next; do
{
res=insert(res, cur1->coef,cur1-
>po_x,cur1->po_y,cur1->po_z);
cur1=cur1->next;
}while(cur1!=p1);

do
{
cur1=res-
>next;
bool
flag1=fals
e; do
{
if(match(cur1,cur2))
{
cur1-
>coef+=cur2-
>coef;
flag1=true;

break;
}
cur1=cur1->next;
}while(cur1!=res);
if(!flag1)
res=insert(res,cur2->coef,cur2-
>po_x,cur2->po_y,cur2->po_z); cur2=cur2-
>next;
}while(cur2!=p2);

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 58


DATA STRUCTURES LABORATORY (BCSL305)

return res;
}

int main()
{
node
p1=(node)malloc(sizeof(
struct node1)); p1-
>next=p1;

node p2=
(node)malloc(sizeof(stru
ct node1)); p2->next=p2;

node res=(node)malloc(sizeof(struct node1));


res->next=res;

p1=insert(p1,+6,2,2,1);
p1=insert(p1,-4,0,1,5);
p1=insert(p1,+3,3,1,1);
p1=insert(p1,+2,1,5,1);
p1=insert(p1,-2,1,1,3);

printf("p1(
X,Y,Z)=
\n");
display(p1)
;

p2=insert(p2,+1,1,1,1);
p2=insert(p2,+4,3,1,1);
printf("p2
(x,y,z)=
\n");
display(p2)
;

res=add(p1,p2,res);

printf("Addition of two
polynomials : res(x,y,z)= \n");
display(res);

int x,y,z;
x=1;
y=2;
z=3;
int ires;

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 59


DATA STRUCTURES LABORATORY (BCSL305)

ires=eval
(res, x,
y ,z);
printf("\n res of polysum(%d,%d,%d): %d) \n ", x,y,z, ires);
return 0;
}

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

ABOUT THE EXPERIMENT:


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)

ALGORITHM:
Step 1: Start.
Step 2: Create a Binary Search Tree for N elements.
Step 3: Traverse the tree in inorder.
Step 4: Traverse the tree in preorder
Step 5: Traverse the tree in postorder.
Step 6: Search the given key element in the BST.
Step 7: Delete an element from BST.
Step 8: Stop

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>

struct BST

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 60


DATA STRUCTURES LABORATORY (BCSL305)

{
int data;
struct BST * lchild;
struct BST * rchild;
};
typedef struct BST * NODE;

NODE create()
{
NODE temp;
temp = (NODE) malloc(sizeof(struct BST));
printf("\nEnter The value: ");
scanf("%d", & temp -> data);temp -> lchild = NULL;
temp -> rchild = NULL;
return temp;
}
void insert(NODE root, NODE newnode);
void inorder(NODE root);
void preorder(NODE root);
void postorder(NODE root);
void search(NODE root);

void insert(NODE root, NODE newnode)


{
/*Note: if newnode->data == root->data it will be skipped. No
duplicate nodes are allowed */
if (newnode -> data < root -> data)
{
if (root -> lchild == NULL)
root -> lchild = newnode;
else
insert(root -> lchild, newnode);
}
if (newnode -> data > root -> data)
{
if (root -> rchild == NULL)
root -> rchild = newnode;
else
insert(root -> rchild, newnode);
}
}

void search(NODE root)


{
int key;
NODE cur;
if (root == NULL)

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 61


DATA STRUCTURES LABORATORY (BCSL305)

{
printf("\nBST is empty.");
return;
}
printf("\nEnter Element to be searched: ");
scanf("%d", & key);
cur = root;
while (cur != NULL)
{
if (cur -> data == key)
{
printf("\nKey element is present in BST");
return;
}
if (key < cur -> data)
cur = cur -> lchild;
else
cur = cur -> rchild;
}
printf("\nKey element is not found in the BST");
}

void inorder(NODE root)


{
if (root != NULL)
{
inorder(root -> lchild);
printf("%d ", root -> data);
inorder(root -> rchild);
}
}

void preorder(NODE root)


{
if (root != NULL)
{
printf("%d ", root -> data);
preorder(root -> lchild);
preorder(root -> rchild);
}
}

void postorder(NODE root)


{
if (root != NULL)
{
postorder(root -> lchild);

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 62


DATA STRUCTURES LABORATORY (BCSL305)

postorder(root -> rchild);


printf("%d ", root -> data);
}
}

void main()
{
int ch, key, val, i, n;
NODE root = NULL, newnode;
while (1)
{
printf("\n~~~~BST MENU~~~~");
printf("\n1.Create a BST");
printf("\n2.Search");
printf("\n3.BST Traversals: ");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nEnter the number of elements: ");
scanf("%d", & n);
for (i = 1; i <= n; i++)
{
newnode = create();
if (root == NULL)
root = newnode;
else
insert(root, newnode);
}
break;

case 2:
if (root == NULL)
printf("\nTree Is Not Created");
else
{
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
case 3:
search(root);
break;
case 4:
exit(0);

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 63


DATA STRUCTURES LABORATORY (BCSL305)

}
}
}
output:
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 1Enter the number of elements: 12
Enter The value: 6
Enter The value: 9
Enter The value: 5
Enter The value: 2
Enter The value: 8
Enter The value: 15
Enter The value: 24
Enter The value: 14
Enter The value: 7
Enter The value: 8
Enter The value: 5
Enter The value: 2~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 3The Preorder display: 6
5 2 9 8 7 15
14 24
The Inorder display: 2 5 6
7 8 9 14 15 24
The Postorder display: 2 5 7
8 14 24 15 9 6~~~~BST
MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2Enter Element to be searched: 66
Key element is not found in the BST~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2Enter Element to be searched: 14
Key element is present in BST~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 4

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 64


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

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 65


DATA STRUCTURES LABORATORY (BCSL305)

ABOUT THE EXPERIMENT:


Adjacency Matrix In graph theory, computer science, an adjacency matrix is a square matrix
used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices
are adjacent or not in the graph. In the special case of a finite simple graph, the adjacency
matrix is a (0, 1)-matrix with zeros on its diagonal.
A graph G = (V, E) where v= {0, 1, 2, . . .n-1} can be represented using two dimensional
integer array of size n x n. a[20][20] can be used to store a graph with 20 vertices. a[i][j] = 1,
indicates presence of edge between two vertices i and j. a[i][j] = 0, indicates absence of edge
between two vertices i and j.
• A graph is represented using square matrix.
• Adjacency matrix of an undirected graph is always a symmetric matrix, i.e. an edge (i, j)
implies the edge (j, i).
• Adjacency matrix of a directed graph is never symmetric, adj[i][j] = 1 indicates a directed
edge from vertex i to vertex j.

ALGORITHM:
Step 1: Start.
Step 2: Input the value of N nodes of the graph
Step 3: Create a graph of N nodes using adjacency matrix representation.
Step 4: Print the nodes reachable from the starting node using BFS.
Step 5: Check whether graph is connected or not using DFS.
Step 6: Stop

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
int a[50][50], n, visited[50];
int q[20], front = -1, rear = -1;
int s[20], top = -1, count = 0;

void bfs(int v)
{
int i, cur;
visited[v] = 1;
q[++rear] = v;
while (front != rear)
{
cur = q[++front];
for (i = 1; i <= n; i++)
{
if ((a[cur][i] == 1) && (visited[i] == 0))
{
q[++rear] = i;
visited[i] = 1;
printf("%d ", i);
}
}
}
}

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 66


DATA STRUCTURES LABORATORY (BCSL305)

void dfs(int v)
{
int i;
visited[v] = 1;
s[++top] = v;
for (i = 1; i <= n; i++)
{
if (a[v][i] == 1 && visited[i] == 0)
{
printf("%d ", i);
dfs(i);
}
}
}

int main()
{
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", & a[i][j]);
}
for (i = 1; i <= n; i++)
visited[i] = 0;
printf("\nEnter the starting vertex: ");
scanf("%d", & start);printf("\n==>1. BFS:
Print all nodes reachable from a given
starting node");
printf("\n==>2. DFS: Print all nodes reachable from a
given starting node");
printf("\n==>3:Exit");
printf("\nEnter your choice: ");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nNodes reachable from
starting vertex %d are: ", start);
bfs(start);
for (i = 1; i <= n; i++)
{
if (visited[i] == 0)
printf("\nThe vertex that is not
reachable is %d", i);
}
break;

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 67


DATA STRUCTURES LABORATORY (BCSL305)

case 2:
printf("\nNodes reachable from
starting vertex %d are:\n", start);
dfs(start);
break;
case 3:
exit(0);
default:
printf("\nPlease enter valid choice:");
}
}
Output:
*************************case-
1*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 1
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 1
Nodes reachable from starting vertex 1 are: 2 4
3*************************case-
2*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 2
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 1
Nodes reachable from starting vertex 2 are: 3 4
The vertex that is not reachable is

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 68


DATA STRUCTURES LABORATORY (BCSL305)

1*************************case-
3*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 1
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 2
Nodes reachable from starting vertex 1 are: 2 3
4*************************case-
4*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 2
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 2
Nodes reachable from starting vertex 2 are: 3 4

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 69


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.

ALGORITHM:
Step 1: Start.
Step 2: Given a File of N employee records with a set K of Keys (4-digit) which uniquely
determine the records in file F.
Step 3: 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.
Step 4: Let the keys in K and addresses in L are Integers
Step 5: Hash function H: K ®L as H(K)=K mod m (remainder method)
Step 6: Hashing as to map a given key K to the address space L, Resolve the collision (if any)
is using linear probing.
Step 7: Stop.

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
int key[20], n, m;
int * ht, index;

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 70


DATA STRUCTURES LABORATORY (BCSL305)

int count = 0;
void insert(int key)
{
index = key % m;
while (ht[index] != -1)
{
index = (index + 1) % m;
}
ht[index] = key;
count++;
}
void display()
{
int i;
if (count == 0)
{
printf("\nHash Table is empty");
return;
}
printf("\nHash Table contents are:\n ");
for (i = 0; i < m; i++)
printf("\n T[%d] --> %d ", i, ht[i]);
}

void main()
{
int i;
printf("\nEnter the number of employee records (N) :");
scanf("%d", & n);
printf("\nEnter the two
digit memory locations (m) for hash table:");
scanf("%d", & m);ht = (int * ) malloc(m * sizeof(int));
for (i = 0; i < m; i++)
ht[i] = -1;
printf("\nEnter the four digit key values (K) for N
Employee Records:\n ");
for (i = 0; i < n; i++)
scanf("%d", & key[i]);for (i = 0; i < n; i++) {
if (count == m)
{
printf("\n~~~Hash table is full.
Cannot insert the record %d key~~~", i + 1);
break;
}
insert(key[i]);
}//Displaying Keys inserted into hash table
display();
}
Output:
Enter the number of employee records (N) :10
Enter the two digit memory locations (m) for hash table:15

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 71


DATA STRUCTURES LABORATORY (BCSL305)

Enter the four digit key values (K) for N Employee Records:
4020
4560
9908
6785
0423
7890
6547
3342
9043
6754
Hash Table contents are:
T[0] --> 4020
T[1] --> 4560
T[2] --> 7890
T[3] --> 423
T[4] --> 6754
T[5] --> 6785
T[6] --> -1
T[7] --> 6547
T[8] --> 9908
T[9] --> -1
T[10] --> -1
T[11] --> -1
T[12] --> 3342
T[13] --> 9043
T[14] --> -1

SAPTHAGIRI COLLEGE OF ENGINEERING, DEPT. OF CSE 72

You might also like