Professional Documents
Culture Documents
DS Record 93
DS Record 93
EX.NO: 1
DATE:
Study of simple node creation using pointers, structures and study of functions.
AIM:
To perform Study Of concept of programming prerequisite Functions, Structures, union,
pointers, arrays and to Create Node Using Pointers, Structures.
ALGORITHM:
PROGRAM:
#include <stdio.h>
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
union un {
SAMPLE OUTPUT:
RESULT:
Thus the Study Of concept of programming prerequisite Functions, Structures, union,
pointers, arrays and to Create Node Using Pointers, Structures has been executed and
compiled successfully.
AIM:
To understand one of the most basic data structures called array. This will help the
studentsas a pre-requisite for most of the complex data structures.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
struct
{
int list[MAX];
int element;
int pos;
int length;
}l;
enum boolean
{
true, false
};
typedef enum boolean boolean;
int menu(void);
void create(void);
void insert(int, int);
void delet(int);
void find(int);
void display(void);
boolean islistfull(void);
boolean islistempty(void);
void main()
{
int ch;
ROLL NO: 2127220501175 PAGE NO: 4
int element;
int pos;
l.length = 0;
while(1)
{
ch = menu();
switch (ch)
{
case 1: l.length = 0;
create();
break;
case 2:
if (islistfull() != true)
{
printf("Enter New element: ");
scanf("%d", &element);
printf("Enter the Position : ");
scanf("%d", &pos);
insert(element, pos);
}
else
{
printf("List is Full. Cannot insert the element");
printf("\n Press any key to continue...");
}
break;
case 3:
if (islistempty() != true)
{
printf("Enter the position of element to be deleted : ");
scanf("%d", &pos);
delet(pos);
}
else
{
printf("List is Empty.");
printf("\n Press any key to continue...");
}
break;
case 4:
printf("No of elements in the list is %d", l.length);
printf("\n Press any key to continue...");
break;
case 5:
printf("Enter the element to be searched :
"); scanf("%d", &element);
find(element);
break;
case 6:
ALGORITHM:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
ROLL NO: 2127220501175 PAGE NO: 10
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
struct Node* constructList()
{
// construct three linked list nodes
struct Node* first = newNode(1);
struct Node* second = newNode(2);
struct Node* third = newNode(3);
struct Node* head = first;
first->next = second;
second->next =
third; return head;
}
void printList(struct Node* head)
{
struct Node* ptr = head;
while (ptr)
{
printf("%d -> ", ptr->data);
ptr = ptr->next;
}
printf("NULL");
}
int main(void)
{
struct Node* head = constructList();
printList(head);
return 0;
}
RESULT:
Thus the implementation of singly linked list using pointers & dynamic memory
allocation has been executed and compiled successfully.
ALGORITHM:
PROGRAM:
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
ROLL NO: 2127220501175 PAGE NO: 12
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
ROLL NO: 2127220501175 PAGE NO: 13
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
RESULT:
Thus the creation of stack using array implementation and pointer implementation has
been executed and compiled successfully.
ALGORITHM:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void display();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Exit"); printf("\
n 5 - Dipslay"); printf("\n 6 -
Stack Count"); create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
int topelement()
{
return(top->info);
}
RESULT:
Thus the creation of stack using array implementation and pointer implementation has
been executed and compiled successfully.
AIM:
To write a C program to convert the given Infix expression to Postfix.
ALGORITHM:
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
RESULT:
Thus the convert the given Infix expression to Postfix has been executed and compiled
successfully.
AIM:
To write a C program to implement the queues using arrays.
ALGORITHM:
RESULT:
Thus the implement the queues using arrays has been executed and compiled successfully.
AIM:
To construct a Binary Search Tree with Tree traversal Techniques – Preorder, Post order
and In order.
ALGORITHM:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct TreeNode* insert(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
void preorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void postorder(struct TreeNode* root) {
ROLL NO: 2127220501175 PAGE NO: 28
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
struct TreeNode* root = NULL;
int choice, data;
do {
printf("\nBinary Search Tree Operations:\n");
printf("1. Insert a node\n");
printf("2. Preorder traversal\n");
printf("3. Inorder traversal\n");
printf("4. Postorder traversal\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2:
printf("Preorder traversal: ");
preorder(root);
printf("\n");
break;
case 3:
printf("Inorder traversal: ");
inorder(root);
printf("\n");
break;
case 4:
printf("Postorder traversal: ");
postorder(root);
printf("\n");
break;
case 5:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);
free(root);
return 0;
RESULT:
Thus the construct a Binary Search Tree with Tree traversal Techniques – Preorder, Post
order and In order has been executed and compiled successfully.
AIM:
To construct a Construct an AVL trees as a balanced search tree and perform the Single
rotation.
ALGORITHM:
RESULT:
Thus the construction of an avl trees as a balanced search tree and perform the single
rotation has been executed and compiled successfully.
AIM:
To perform Breadth First Search algorithm in graph data structure.
ALGORITHM:
1. Define a `Graph` structure
RESULT:
Thus the graph traversal algorithm - breadth-first search has been executed and compiled
successfully.
AIM:
To perform Depth First Search algorithm in graph data structure.
ALGORITHM:
1. Define a `node` structure:
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v);
struct Graph {
int totalVertices;
int* visited;
struct node** adjLists;
};
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1;
printf("%d -> ", vertex);
while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->totalVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct node* newNode = createNode(dest);
AIM:
To perform the single source shortest path in an undirected graph using Dijkstra’s
algorithm.
ALGORITHM:
1. Define a function `minDistance` to find the vertex with the minimum distance value
from the set of vertices not yet included in the shortest path tree (`sptSet`). It iterates
through all vertices and returns the index of the vertex with the minimum distance.
2. Define a function `printSolution` to print the computed distances from the source vertex
to all other vertices.
#include <stdio.h>
#include <limits.h>
#define V 9
int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
int v;
for (v = 0; v < V; v++)
if (sptSet[v] == 0 && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
int i;
for (i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
int sptSet[V];
int i, count,
v;
for (i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = 0;
dist[src] = 0;
for (count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = 1;
for (v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]
+ graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
RESULT:
Thus the single source shortest path in an undirected graph using Dijkstra’s algorithm has
been executed and compiled successfully.
ALGORITHM:
1. Define a custom comparator function (`comparator`) for sorting the edges in non-
decreasing order based on their weights.
3. Define the `findParent` function, which uses path compression to find the
representative (parent) of a given component in the disjoint-set data structure. It
recursively finds the parent and updates the parent of each visited node along the path
to the root for efficient future queries.
4. Define the `unionSet` function, which performs the union operation to merge two
components into a single component in the disjoint-set data structure. It takes two vertices
`u` and `v`, finds their parents, and merges them based on the rank (depth) of their
respective trees. The rank is used to optimize the union operation by attaching the tree
with the smaller rank to the tree with the larger rank.
5. Define the `kruskalAlgo` function, which finds the Minimum Spanning Tree (MST) of
the graph:
- Sort the edges in non-decreasing order based on their weights using `qsort` and the
`comparator` function.
- Initialize arrays for parent and rank for the disjoint-set data structure using `makeSet`.
- Initialize `minCost` to 0, which will store the total weight of the MST.
- Iterate through the sorted edges:
- For each edge, check if its two vertices belong to different components (sets) using
`findParent`.
- If they are not in the same component, add this edge to the MST, update the
parent and rank arrays with `unionSet`, and increment `minCost` by the weight of the
edge.
- Print the edge that is added to the MST.
- After processing all edges, the MST is constructed, and its minimum cost is calculated.
- Print the edges in the MST and the total minimum cost.
#include <stdio.h>
#include <stdlib.h>
int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;
return (*x)[2] - (*y)[2];
}
void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++)
{ parent[i] = i;
rank[i] = 0;
}
}
int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;
return parent[component]
= findParent(parent, parent[component]);
}
void unionSet(int u, int v, int parent[], int rank[], int n)
{
u = findParent(parent,
u); v = findParent(parent,
v); if (rank[u] < rank[v])
{
parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u; rank[u]+
+;
}
}
void kruskalAlgo(int n, int edge[n][3])
{
qsort(edge, n, sizeof(edge[0]), comparator);
int parent[n];
int rank[n];
makeSet(parent, rank, n);
int minCost = 0;
printf(
ROLL NO: 2127220501175 PAGE NO: 50
"Following are the edges in the constructed MST\n");
RESULT:
Thus the Construction of the Minimum Spanning Tree using Kruskal's algorithm. It is a
way of finding the most economical way to connect a set of vertices has been executed
and compiled successfully.
AIM:
To write a C program to implement Insertion Sort.
ALGORITHM:
1. Define a function `display` to print the elements of an array.
- Iterate through the array and print each element.
#include <stdio.h>
void display(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int tmp = arr[i];
int j = i - 1;
while (tmp < arr[j] && j >= 0) {
arr[j + 1] = arr[j];
--j;
}
arr[j + 1] = tmp;
}
}
int main() {
int arr[] = {9, 5, 1, 4, 3};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Elements before sorting:\n");
display(arr, n);
insertionSort(arr, n);
printf("Elements after sorting:\n");
display(arr, n);
}
RESULT:
Thus the implementation of sorting – insertion sort has been executed and compiled
successfully.
ALGORITHM:
#include <stdio.h>
void bubbleSort(int array[], int size) {
for (int step = 0; step < size - 1; ++step)
{ for (int i = 0; i < size - step - 1; ++i) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
printf("Sorted Array in Ascending Order:\n");
printArray(data, size);
}
RESULT:
Thus the implementation of bubble sort has been executed and compiled successfully.
AIM:
To write a C program to implement Quick Sort.
ALGORITHM:
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int array[], int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++)
{ if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);
}
RESULT:
Thus the implementation of quick sort has been executed and compiled successfully.
AIM:
ALGORITHM:
1. Define a structure called `node` to represent a node in a singly-linked list. Each node
contains an integer data value and a pointer to the next node in the list.
2. Define an array of pointers called `chain` of size `size` (set to 7 in this case) to
represent the hash table. Each element of this array is a pointer to the head of a
linked list.
3. Define an `init` function to initialize the hash table. It sets all elements in the `chain`
array to `NULL`, indicating that there are no elements in the hash table initially.
4. Define an `insert` function to insert an integer value into the hash table:
- Calculate the key by taking the remainder of the value divided by the size of the
hash table (`value % size`).
- If the linked list at the calculated key is empty (i.e., `chain[key]` is `NULL`), set the
new node as the head of the list.
- If the linked list at the calculated key is not empty, traverse the list to find the end,
and then append the new node to the end of the list.
- Iterate through each element in the `chain` array (i.e., each linked list).
- For each linked list, traverse the nodes and print the data values.
Insert several values (e.g., 15, 11, 27, 8) into the hash table using the `insert` function.
#include<stdio.h>
#include<stdlib.h>
#define size 7
struct node
int data;
};
void init()
int i;
chain[i] = NULL;
newNode->data = value;
newNode->next = NULL;
if(chain[key] == NULL)
chain[key] = newNode;
else
temp = temp->next;
temp->next = newNode;
void print()
int i;
printf("chain[%d]-->",i);
while(temp)
printf("%d -->",temp->data);
temp = temp->next;
printf("NULL\n");
int main()
init();
insert(15);
insert(11);
insert(8);
print();
return 0;
RESULT:
Thus the hashing implementation of separate chaining has been executed and compiled
successfully.
AIM:
To write a C program for Linear probing techniques.
ALGORITHM:
1. Define an array `h` of size `TABLE_SIZE` (set to 10 in this case) to represent the
hash table. Each element of this array will store an integer value or be initialized to
`NULL`.
2. Define a function `insert` to insert an integer value into the hash table:
- Prompt the user to enter a value to insert.
- Calculate the hash key by taking the remainder of the value divided by the size of the
hash table (`key % TABLE_SIZE`).
- Use linear probing to find the appropriate index for insertion:
- Start with the calculated hash key (`hkey`) and check the element at that index.
- If the element is `NULL`, insert the value at that index and break.
- If the element is not `NULL`, increment the index (`hkey + 1`) and check the next
index.
- Continue this process until an empty slot is found or until the entire hash table is
checked.
- If the loop finishes without finding an empty slot, print a message indicating that the
element cannot be inserted.
PROGRAM:
#include <stdio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("\nenter a value to insert into hash table\n");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
}
if(i == TABLE_SIZE)
printf("\nelement cannot be inserted\n");
}
void search()
{
int key,index,i,flag=0,hkey; printf("\
nenter search element\n");
scanf("%d",&key); hkey=key
%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index]==key)
{
printf("value is found at index %d",index);
break;
}
}
if(i == TABLE_SIZE)
ROLL NO: 2127220501175 PAGE NO: 65
printf("\n value is not found\n");
}
void display()
{
int i;
printf("\nelements in the hash table are \n");
for(i=0;i< TABLE_SIZE; i++)
printf("\nat index %d \t value = %d",i,h[i]);
}
main()
{
int opt,i;
while(1)
{
printf("\nPress 1. Insert\t 2. Display \t3. Search \t4.Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:exit(0);
}
}
}
RESULT:
Thus the hashing implementation of open addressing (linear probing) has been executed
and compiled successfully.