Suraj Dsa

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q1. Write a C program to create a single linked list, then write another function to swap
nodes pairwise.
Input: 11->12->13->14->15->16->NULL
Output : 12->11->14->13->16->15->NULL

Source-Code
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node


typedef struct Node
{
int data;
struct Node *next;
} Node;

// Function to create a new node


Node *createNode(int data)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the list


void insertEnd(Node **head, int data)
{
Node *newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
return;
}
Node *temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}

// Function to display the linked list


void displayList(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

}
printf("NULL\n");
}

// Function to swap nodes pairwise


void swapNodesPairwise(Node **head)
{
if (*head == NULL || (*head)->next == NULL)
return;

Node *prev = *head;


Node *curr = (*head)->next;

// Swap the first two nodes to make the second node the new head
*head = curr;

while (1)
{
Node *next = curr->next;
curr->next = prev;

if (next == NULL || next->next == NULL)


{
prev->next = next;
break;
}

prev->next = next->next;
prev = next;
curr = prev->next;
}
}

// Function to display the menu and handle user input


int main()
{
Node *head = NULL;
int choice, data;

while (1)
{
printf("\nMenu:\n");
printf("1. Insert node at end\n");
printf("2. Display list\n");
printf("3. Swap nodes pairwise\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

{
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertEnd(&head, data);
break;
case 2:
printf("Linked list: ");
displayList(head);
break;
case 3:
swapNodesPairwise(&head);
printf("Nodes swapped pairwise.\n");
break;
case 4:
printf("Exiting...\n");
exit(0);
break;
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q2. Write a C program to create a single linked list, then write another function InsertNth()
which can insert a new node after any node given by the user in that linked list.

Source-Code
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node


struct node
{
int data;
struct node *next;
};

// Function to create a new node


struct node *createNode(int data)
{
struct node *newNode = (struct node *)malloc(sizeof(struct node));
if (!newNode)
{
printf("Memory allocation error\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the list


void insertEnd(struct node **head, int data)
{
struct node *newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
return;
}
struct node *temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}

// Function to display the linked list


void displayList(struct node *head)
{
if (head == NULL)
{
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

printf("List is empty\n");
return;
}
struct node *temp = head;
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Function to insert a node after a specified node


void InsertNth(struct node **head, int data, int n)
{
struct node *newNode = createNode(data);
struct node *temp = *head;
while (temp != NULL && temp->data != n)
{
temp = temp->next;
}
if (temp == NULL)
{
printf("Node with value %d not found\n", n);
free(newNode);
}
else
{
newNode->next = temp->next;
temp->next = newNode;
}
}

// Function to display the menu and handle user input


int main()
{
struct node *head = NULL;
int choice, data, n;

while (1)
{
printf("\nMenu:\n");
printf("1. Insert node at end\n");
printf("2. Display list\n");
printf("3. Insert node after specified node\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

{
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertEnd(&head, data);
break;
case 2:
printf("Linked list: ");
displayList(head);
break;
case 3:
printf("Enter data to insert: ");
scanf("%d", &data);
printf("Enter the node value after which to insert: ");
scanf("%d", &n);
InsertNth(&head, data, n);
break;
case 4:
printf("Exiting...\n");
exit(0);
break;
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q3. Write a C program to create a double linked list, write another C function which takes
the address of the
linked list and two integers M and N.
Traverse the linked list such that you retain M nodes then delete next N nodes of the
linked list.
Input:
M = 2, N = 2
Linked List: 11<-->12<->13<->14<->15<->16<->17<->18
Output:
Linked List: 11->12->15->16<->17<->18

Source-Code

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

// Define the structure of a node


struct node
{
int data;
struct node *prev;
struct node *next;
};

// Function to create a new node


struct node *createNode(int data)
{
struct node *newNode = (struct node *)malloc(sizeof(struct node));
if (!newNode)
{
printf("Memory allocation error\n");
exit(1);
}
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the list


void insertEnd(struct node **head, int data)
{
struct node *newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
return;
}
struct node *temp = *head;
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

while (temp->next != NULL)


{
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}

// Function to display the linked list


void displayList(struct node *head)
{
if (head == NULL)
{
printf("List is empty\n");
return;
}
struct node *temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Function to retain M nodes and delete the next N nodes


void retainAndDelete(struct node **head, int M, int N)
{
struct node *current = *head;
struct node *temp;

while (current != NULL)


{
// Retain M nodes
for (int i = 1; i < M && current != NULL; i++)
{
current = current->next;
}

// If we've reached the end of the list, break


if (current == NULL)
{
break;
}

// Delete the next N nodes


temp = current->next;
for (int i = 1; i <= N && temp != NULL; i++)
{
struct node *next = temp->next;
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

free(temp);
temp = next;
}

// Connect the M-th node to the (M+N+1)-th node


current->next = temp;
if (temp != NULL)
{
temp->prev = current;
}

// Move current to the next retained node


current = temp;
}
}

int main()
{
struct node *head = NULL;
int choice, data, M, N;

while (1)
{
printf("\nMenu:\n");
printf("1. Insert node at end\n");
printf("2. Display list\n");
printf("3. Retain M nodes and delete N nodes\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertEnd(&head, data);
break;
case 2:
printf("Linked list: ");
displayList(head);
break;
case 3:
printf("Enter the value of M: ");
scanf("%d", &M);
printf("Enter the value of N: ");
scanf("%d", &N);
retainAndDelete(&head, M, N);
break;
case 4:
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

printf("Exiting...\n");
exit(0);
break;
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q4. Write a C program to create a linked list P, then write a ‘C’ function named split
to create two linked lists Q & R from P So that Q contains all elements in odd
positions of P and R contains the remaining elements. Finally print both linked lists i.e.
Q and R.
Source-Code

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

// Define the structure of a node


struct node
{
int data;
struct node *next;
};

// Function to create a new node


struct node *createNode(int data)
{
struct node *newNode = (struct node *)malloc(sizeof(struct node));
if (!newNode)
{
printf("Memory allocation error\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the list


void insertEnd(struct node **head, int data)
{
struct node *newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
return;
}
struct node *temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

// Function to display the linked list


void displayList(struct node *head)
{
if (head == NULL)
{
printf("List is empty\n");
return;
}
struct node *temp = head;
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Function to split the list into two lists Q and R


void split(struct node *P, struct node **Q, struct node **R)
{
int position = 1;
while (P != NULL)
{
if (position % 2 == 1)
{
insertEnd(Q, P->data);
}
else
{
insertEnd(R, P->data);
}
P = P->next;
position++;
}
}

int main()
{
struct node *P = NULL;
struct node *Q = NULL;
struct node *R = NULL;
int choice, data;

while (1)
{
printf("\nMenu:\n");
printf("1. Insert node at end\n");
printf("2. Display list P\n");
printf("3. Split list into Q and R\n");
printf("4. Display lists Q and R\n");
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertEnd(&P, data);
break;
case 2:
printf("Linked list P: ");
displayList(P);
break;
case 3:
split(P, &Q, &R);
printf("List P splited into Q and R.\n");
break;
case 4:
printf("Linked list Q (odd positions): ");
displayList(Q);
printf("Linked list R (even positions): ");
displayList(R);
break;
case 5:
printf("Exiting...\n");
exit(0);
break;
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q5. W.A.P. to create a binary search tree and perform following operations:
1) Count nodes having left child only in the binary search tree
2) Print node having smallest information in the binary search tree
3) Count total number of leaf nodes
4) Count nodes having both children in the binary search tree
5) Count total numbers of nodes from right hand side of root node

Source-Code

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

// Definition of a tree node


struct Node
{
int data;
struct Node *left;
struct Node *right;
};

// Function to create a new node


struct Node *createNode(int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a new node in the BST


struct Node *insertNode(struct Node *root, int data)
{
if (root == NULL)
{
return createNode(data);
}
if (data < root->data)
{
root->left = insertNode(root->left, data);
}
else if (data > root->data)
{
root->right = insertNode(root->right, data);
}
return root;
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

// Function to count nodes having only left child


int countLeftChildOnly(struct Node *root)
{
if (root == NULL)
return 0;
int count = 0;
if (root->left != NULL && root->right == NULL)
{
count = 1;
}
return count + countLeftChildOnly(root->left) + countLeftChildOnly(root->right);
}

// Function to find the node with the smallest value


struct Node *findMinNode(struct Node *root)
{
struct Node *current = root;
while (current && current->left != NULL)
{
current = current->left;
}
return current;
}

// Function to count total number of leaf nodes


int countLeafNodes(struct Node *root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
return countLeafNodes(root->left) + countLeafNodes(root->right);
}

// Function to count nodes having both children


int countBothChildren(struct Node *root)
{
if (root == NULL)
return 0;
int count = 0;
if (root->left != NULL && root->right != NULL)
{
count = 1;
}
return count + countBothChildren(root->left) + countBothChildren(root->right);
}

// Function to count total number of nodes from the right-hand side of the root node
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

int countRightNodes(struct Node *root)


{
if (root == NULL)
return 0;
return 1 + countRightNodes(root->left) + countRightNodes(root->right);
}

int main()
{
struct Node *root = NULL;
int choice, value;

while (1)
{
printf("\n1. Insert\n2. Count nodes with left child only\n3. Print node with smallest
value\n4. Count leaf nodes\n5. Count nodes with both children\n6. Count nodes from right-
hand side of root\n7. Exit\nEnter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
root = insertNode(root, value);
break;
case 2:
printf("Nodes with left child only: %d\n", countLeftChildOnly(root));
break;
case 3:
{ struct Node *minNode = findMinNode(root);
if (minNode != NULL)
{ printf("Node with smallest value: %d\n", minNode->data);
}
else
{ printf("Tree is empty.\n");}}
break;
case 4: printf("Total number of leaf nodes: %d\n", countLeafNodes(root));
break;
case 5: printf("Nodes with both children: %d\n", countBothChildren(root));
break;
case 6: printf("Nodes from right-hand side of root: %d\n", countRightNodes(root-
>right));
break; case 7:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q6. Write a program to add of two polynomials of degree n, using linked list For example
p1=anxn+an-1xn-1 + an-2xn-2 + a0x0
P2=bnxn+bn-1xn-1 + bn-2xn-2 +........b0x0
p1 = first polynomial

p2 = second polynomial

Find out p3= p1+p2

Source-Code

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

// Definition of a node in the linked list


struct Node
{
int coefficient;
int exponent;
struct Node *next;
};

// Function to create a new node


struct Node *createNode(int coefficient, int exponent)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = NULL;
return newNode;
}

// Function to insert a new node into the linked list in decreasing order of exponents
struct Node *insertNode(struct Node *head, int coefficient, int exponent)
{
struct Node *newNode = createNode(coefficient, exponent);
if (head == NULL || head->exponent < exponent)
{
newNode->next = head;
return newNode;
}

struct Node *current = head;


while (current->next != NULL && current->next->exponent > exponent)
{
current = current->next;
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

}
newNode->next = current->next;
current->next = newNode;

return head;
}

// Function to add two polynomials and return the resultant polynomial


struct Node *addPolynomials(struct Node *p1, struct Node *p2)
{
struct Node *result = NULL;
struct Node *t1 = p1;
struct Node *t2 = p2;

while (t1 != NULL && t2 != NULL)


{
if (t1->exponent == t2->exponent)
{
result = insertNode(result, t1->coefficient + t2->coefficient, t1->exponent);
t1 = t1->next;
t2 = t2->next;
}
else if (t1->exponent > t2->exponent)
{
result = insertNode(result, t1->coefficient, t1->exponent);
t1 = t1->next;
}
else
{
result = insertNode(result, t2->coefficient, t2->exponent);
t2 = t2->next;
}
}

// Add remaining nodes of p1


while (t1 != NULL)
{
result = insertNode(result, t1->coefficient, t1->exponent);
t1 = t1->next;
}

// Add remaining nodes of p2


while (t2 != NULL)
{
result = insertNode(result, t2->coefficient, t2->exponent);
t2 = t2->next;
}

return result;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

// Function to print the polynomial


void printPolynomial(struct Node *head)
{
struct Node *current = head;
while (current != NULL)
{
if (current->coefficient != 0)
{
printf("%dx^%d", current->coefficient, current->exponent);
if (current->next != NULL && current->next->coefficient >= 0)
{
printf(" + ");
}
}
current = current->next;
}
printf("\n");
}

int main()
{
struct Node *p1 = NULL;
struct Node *p2 = NULL;
struct Node *p3 = NULL;
int choice, degree, coefficient;

while (1)
{
printf("\nMenu:\n");
printf("1. Enter first polynomial\n");
printf("2. Enter second polynomial\n");
printf("3. Add polynomials\n");
printf("4. Display polynomials\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
p1 = NULL;
printf("Enter the degree of the first polynomial: ");
scanf("%d", &degree);
printf("Enter the coefficients of the first polynomial (highest to lowest degree):\n");
for (int i = degree; i >= 0; i--)
{
printf("Coefficient of x^%d: ", i);
scanf("%d", &coefficient);
p1 = insertNode(p1, coefficient, i);
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

}
break;

case 2:
p2 = NULL;
printf("Enter the degree of the second polynomial: ");
scanf("%d", &degree);
printf("Enter the coefficients of the second polynomial (highest to lowest degree):\n");
for (int i = degree; i >= 0; i--)
{
printf("Coefficient of x^%d: ", i);
scanf("%d", &coefficient);
p2 = insertNode(p2, coefficient, i);
}
break;

case 3:
p3 = addPolynomials(p1, p2);
printf("Polynomials added.\n");
break;

case 4:
printf("First polynomial: ");
printPolynomial(p1);
printf("Second polynomial: ");
printPolynomial(p2);
if (p3 != NULL)
{
printf("Resultant polynomial (p1 + p2): ");
printPolynomial(p3);
}
else
{
printf("Resultant polynomial not yet computed.\n");
}
break;

case 5:
exit(0);

default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q7. Write a C program to sort a sequence of characters given by user in an array, using
Quick sort technique.
Source-Code

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

// Function to swap two characters


void swap(char* a, char* b) {
char temp = *a;
*a = *b;
*b = temp;
}

// Partition function for Quick Sort


int partition(char arr[], int low, int high) {
char pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high - 1; j++) {


// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// Quick Sort function


void quickSort(char arr[], int low, int high) {
if (low < high) {
// pi is partitioning index, arr[p] is now at right place
int pi = partition(arr, low, high);

// Separately sort elements before partition and after partition


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Function to print array


void printArray(char arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%c ", arr[i]);
}
printf("\n");
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

int main() {
char* arr = NULL;
int n = 0;
int choice;
do {
printf("\nMenu:\n");
printf("1. Enter characters\n");
printf("2. Sort characters using Quick Sort\n");
printf("3. Display characters\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the number of characters: ");
scanf("%d", &n);
arr = (char*)malloc(n * sizeof(char));
printf("Enter the characters: ");
for (int i = 0; i < n; i++) {
scanf(" %c", &arr[i]);
}
break;

case 2:
if (arr != NULL) {
quickSort(arr, 0, n - 1);
printf("Characters sorted successfully.\n");
} else {
printf("No characters to sort. Please enter characters first.\n");
}
break;

case 3:
if (arr != NULL) {
printf("Characters: ");
printArray(arr, n);
} else {
printf("No characters to display. Please enter characters first.\n");}
break;
case 4:
free(arr);
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
} } while (choice != 4);

return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q8. Using circular linked list allocate time slots of 10ms for given processes in
time sharing Environment and then print, which process will be completed
in how much time.
Source-Code

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

typedef struct Process {


int id;
int burst_time;
int remaining_time;
int completion_time;
struct Process *next;
} Process;

void Allocate(Process **head, int id) {


Process *ptr = (Process *)malloc(sizeof(Process));
printf("Enter Burst time of process id %d: ", id);
scanf("%d", &ptr->burst_time);
ptr->id = id;
ptr->remaining_time = ptr->burst_time;
ptr->completion_time = 0;

if (*head == NULL) {
*head = ptr;
(*head)->next = ptr;
} else {
Process *temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = ptr;
ptr->next = *head;
}
}

void MultiProgramming(Process *head, int TIME_SLOT) {


if (head == NULL) {
printf("\nNo processes to run.\n");
return;
}

Process *tmp = head;


Process *current = head;
int total_time = 0;
int flag = 0;

do {
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

flag = 0;
do {
if (current->remaining_time > 0) {
if (current->remaining_time > TIME_SLOT) {
current->remaining_time -= TIME_SLOT;
total_time += TIME_SLOT;
} else {
total_time += current->remaining_time;
current->remaining_time = 0;
current->completion_time = total_time;
}
}
current = current->next;
} while (current != head);

tmp = head;
while (tmp != NULL) {
if (tmp->remaining_time > 0) {
flag = 1;
break;
}
tmp = tmp->next;
if (tmp == head) break;
}
} while (flag);

printf("Successfully Performed multiprogramming.\n");


}

void Display(Process *head) {


if (head == NULL) {
printf("\nNo processes to display.\n");
return;
}

Process *tmp = head;


do {
printf("Process ID: %d, Burst Time: %d, Completion Time: %d\n", tmp->id, tmp-
>burst_time, tmp->completion_time);
tmp = tmp->next;
} while (tmp != head);
}

int main() {
Process *head = NULL;
int time_slot, choice, id = 1;

printf("Menu:\n");
printf("1. Allocate time\n");
printf("2. Perform multiprogramming\n");
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

printf("3. Display each process details\n");


printf("4. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
Allocate(&head, id);
id++;
break;
case 2:
if (head == NULL) {
printf("\nNo processes are running\n");
} else {
printf("Enter time slot: ");
scanf("%d", &time_slot);
MultiProgramming(head, time_slot);
}
break;
case 3:
Display(head);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);

return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q9. Write a c program to implement Kruskal’s algorithm in a weighted graph, to find


minimum spanning tree and also print the edges which will be part of the minimal spanning
tree and the total weight .

Source-Code

#include <stdio.h>
#include <stdlib.h>
struct Edge {
int src, dest, weight;
};

// Structure to represent a graph


struct Graph {
int V, E;
struct Edge* edges;
};

// Structure to represent a subset for union-find


struct Subset {
int parent;
int rank;
};

// Function to find the set of an element i (uses path compression technique)


int find(struct Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

// Function to do union of two subsets x and y (uses union by rank)


void Union(struct Subset subsets[], int x, int y) {
int rootX = find(subsets, x);
int rootY = find(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank) {


subsets[rootX].parent = rootY;
} else if (subsets[rootX].rank > subsets[rootY].rank) {
subsets[rootY].parent = rootX;
} else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}

// Compare function used by qsort


int compare(const void* a, const void* b) {
struct Edge* a1 = (struct Edge*)a;
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

struct Edge* b1 = (struct Edge*)b;


return a1->weight - b1->weight;
}

// Function to construct and print the MST using Kruskal's algorithm


void KruskalMST(struct Graph* graph) {
int V = graph->V;
struct Edge result[V]; // This will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges

// Step 1: Sort all the edges in non-decreasing order of their weight


qsort(graph->edges, graph->E, sizeof(graph->edges[0]), compare);

// Allocate memory for creating V subsets


struct Subset* subsets = (struct Subset*)malloc(V * sizeof(struct Subset));

// Create V subsets with single elements


for (int v = 0; v < V; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;
}

// Number of edges to be taken is equal to V-1


while (e < V - 1 && i < graph->E) {
// Step 2: Pick the smallest edge. Check if it forms a cycle with the spanning tree formed
so far.
struct Edge next_edge = graph->edges[i++];

int x = find(subsets, next_edge.src);


int y = find(subsets, next_edge.dest);

// If including this edge does not cause a cycle, include it in the result and increment the
index of the result for the next edge
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}

// Print the contents of the result[] to display the built MST


printf("Following are the edges in the constructed MST\n");
int total_weight = 0;
for (i = 0; i < e; ++i) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);
total_weight += result[i].weight;
}
printf("Total weight of MST is %d\n", total_weight);
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

free(subsets);
}

int main() {
int V, E;
printf("Enter number of vertices: ");
scanf("%d", &V);
printf("Enter number of edges: ");
scanf("%d", &E);

struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));


graph->V = V;
graph->E = E;

graph->edges = (struct Edge*)malloc(graph->E * sizeof(struct Edge));

for (int i = 0; i < E; ++i) {


printf("Enter source, destination and weight of edge %d: ", i + 1);
scanf("%d %d %d", &graph->edges[i].src, &graph->edges[i].dest,
&graph>edges[i].weight);
}

KruskalMST(graph);

free(graph->edges);
free(graph);

return 0;
}
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

Q10. Write a c program to implement DFS.

Source-Code

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

#define MAX 100

struct Node {
int vertex;
struct Node* next;
};

struct Graph {
int numVertices;
struct Node** adjLists;
int* visited;
};

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->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct Node*));
graph->visited = malloc(vertices * sizeof(int));

for (int i = 0; i < vertices; i++) {


graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}

return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {


// Add edge from src to dest
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src (because the graph is undirected)


newNode = createNode(src);
newNode->next = graph->adjLists[dest];
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

graph->adjLists[dest] = newNode;
}

void DFS(struct Graph* graph, int vertex) {


struct Node* adjList = graph->adjLists[vertex];
struct Node* temp = adjList;

graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);

while (temp != NULL) {


int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

void resetVisited(struct Graph* graph) {


for (int i = 0; i < graph->numVertices; i++) {
graph->visited[i] = 0;
}
}

int main() {
int vertices, choice, src, dest, startVertex;

printf("Enter the number of vertices in the graph: ");


scanf("%d", &vertices);

struct Graph* graph = createGraph(vertices);

while (1) {
printf("\nMenu\n");
printf("1. Add edge\n");
printf("2. Perform DFS\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter source and destination vertices: ");
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
break;
case 2:
printf("Enter the starting vertex for DFS: ");
scanf("%d", &startVertex);
NAME: - SURAJ SINGH NEGI COURSE/SEM-MCA/2 ROLL NO/SEC- 2301400(63)/B

resetVisited(graph);
printf("Depth First Traversal starting from vertex %d:\n", startVertex);
DFS(graph, startVertex);
break;
case 3:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

You might also like