0% found this document useful (0 votes)
34 views30 pages

Dsafile

This C program implements a queue using a linked list to store product information. It defines structs for a Product node containing product details and a Queue node containing a front and rear pointer. Functions are created to initialize an empty queue, add products to the queue, remove products from the queue, and check if the queue is empty. The main function demonstrates enqueueing and dequeueing products and printing their details.

Uploaded by

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

Dsafile

This C program implements a queue using a linked list to store product information. It defines structs for a Product node containing product details and a Queue node containing a front and rear pointer. Functions are created to initialize an empty queue, add products to the queue, remove products from the queue, and check if the queue is empty. The main function demonstrates enqueueing and dequeueing products and printing their details.

Uploaded by

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

/*Q1.

Write a C program to Insert and Delete elements form a


Queue using link list ,each node
should have the following inforamaion about a product
Product_Id(char) , Product_Name(string) ,
Total_sale(integer),Product_Grade(Char) */

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

struct Product
{
char Product_Id;
char Product_Name[50];
int Total_sale;
char Product_Grade;
};

typedef struct Product Product;

struct Node
{
Product productData;
struct Node *next;
};

typedef struct Node Node;

struct Queue
{
Node *front;
Node *rear;
};

typedef struct Queue Queue;

Node *createNode(Product product)


{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->productData = product;
newNode->next = NULL;
return newNode;
}

Queue *createQueue()
{
Queue *queue = (Queue *)malloc(sizeof(Queue));
queue->front = NULL;
queue->rear = NULL;
return queue;
}
int isEmpty(Queue *queue)
{
return queue->front == NULL;
}

void enqueue(Queue *queue, Product product)


{
Node *newNode = createNode(product);

if (isEmpty(queue))
{
queue->front = newNode;
queue->rear = newNode;
}
else
{
queue->rear->next = newNode;
queue->rear = newNode;
}
}

Product dequeue(Queue *queue)


{
if (isEmpty(queue))
{
printf("Queue is empty\n");
exit(EXIT_FAILURE);
}

Node *temp = queue->front;


Product product = temp->productData;

queue->front = queue->front->next;
free(temp);

return product;
}

int main()
{
Queue *queue = createQueue();

Product product1 = {'A', "Product1", 100, 'A'};


Product product2 = {'B', "Product2", 150, 'B'};
Product product3 = {'C', "Product3", 200, 'A'};

enqueue(queue, product1);
enqueue(queue, product2);
enqueue(queue, product3);
while (!isEmpty(queue))
{
Product product = dequeue(queue);
printf("Product ID: %c, Name: %s, Total Sale: %d, Grade:
%c\n", product.Product_Id, product.Product_Name,
product.Total_sale, product.Product_Grade);
}

return 0;
}
/* OUTPUT:-
Product ID: A, Name: Product1, Total Sale: 100, Grade: A
Product ID: B, Name: Product2, Total Sale: 150, Grade: B
Product ID: C, Name: Product3, Total Sale: 200, Grade: A */
/*Q2.Let A and B be two structures of type Linked List. Write a
‘C ’ program to create a new
Linked List ‘S’ that contains elements alternately from A and B
beginning with the first
element of A. If you run out of elements in one of the lists,
then append the remaining*/

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

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

typedef struct Node Node;

struct LinkedList {
Node* head;
Node* tail;
};

typedef struct LinkedList LinkedList;

Node* createNode(int data) {


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

void insertAtEnd(LinkedList* list, int data) {


Node* newNode = createNode(data);
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
} else {
list->tail->next = newNode;
list->tail = newNode;
}
}

void createAlternatingList(LinkedList* A, LinkedList* B,


LinkedList* S) {
Node* currA = A->head;
Node* currB = B->head;

while (currA != NULL && currB != NULL) {


insertAtEnd(S, currA->data);
insertAtEnd(S, currB->data);
currA = currA->next;
currB = currB->next;
}

while (currA != NULL) {


insertAtEnd(S, currA->data);
currA = currA->next;
}

while (currB != NULL) {


insertAtEnd(S, currB->data);
currB = currB->next;
}
}

void displayList(LinkedList* list) {


Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {

LinkedList A = {NULL, NULL};


LinkedList B = {NULL, NULL};

insertAtEnd(&A, 1);
insertAtEnd(&A, 3);
insertAtEnd(&A, 5);

insertAtEnd(&B, 2);
insertAtEnd(&B, 4);
insertAtEnd(&B, 6);
insertAtEnd(&B, 8);

LinkedList S = {NULL, NULL};


createAlternatingList(&A, &B, &S);
printf("List S: ");
displayList(&S);

return 0;
}
/*OUTPUT:-
List S: 1 2 3 4 5 6 8
*/

/*Q3.Write a C program to create a single linked list then input


a value V, partition it such that all nodes less
than V come before nodes greater than or equal to V.*/

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

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

typedef struct Node Node;

Node* createNode(int data) {


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

void insertAtEnd(Node** head, int data) {


Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

Node* partitionList(Node* head, int V) {


Node* lessThanV = NULL;
Node* greaterThanOrEqualV = NULL;
Node* current = head;

while (current != NULL) {


if (current->data < V) {
insertAtEnd(&lessThanV, current->data);
} else {
insertAtEnd(&greaterThanOrEqualV, current->data);
}
current = current->next;
}

if (lessThanV != NULL) {
current = lessThanV;
while (current->next != NULL) {
current = current->next;
}
current->next = greaterThanOrEqualV;
return lessThanV;
} else {
return greaterThanOrEqualV;
}
}

void displayList(Node* head) {


Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* head = NULL;

insertAtEnd(&head, 3);
insertAtEnd(&head, 6);
insertAtEnd(&head, 1);
insertAtEnd(&head, 5);
insertAtEnd(&head, 2);
insertAtEnd(&head, 7);

int V = 4;

printf("Original List: ");


displayList(head);

head = partitionList(head, V);

printf("Partitioned List: ");


displayList(head);

return 0;
}
/*OUTPUT:-
Original List: 3 6 1 5 2 7
Partitioned List: 3 1 2 6 5 7
*/

/*Q4.Write a C program to create two single linked lists, and


then write another function to subtract two
numbers represented as linked list.
List1->; 8->9->7->NULL (First Number: 897)
List2->: 1->4->5->NULL (Second Number: 145)
Output->:752*/

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

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

typedef struct Node Node;

Node* createNode(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertAtEnd(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

Node* reverseList(Node* head) {


Node *prev, *current, *next;
prev = NULL;
current = head;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}

Node* subtractLists(Node* list1, Node* list2) {


list1 = reverseList(list1);
list2 = reverseList(list2);

Node* result = NULL;


int borrow = 0;

while (list1 != NULL || list2 != NULL) {


int data1 = (list1 != NULL) ? list1->data : 0;
int data2 = (list2 != NULL) ? list2->data : 0;

int sub = data1 - data2 - borrow;


if (sub < 0) {
sub += 10;
borrow = 1;
} else {
borrow = 0;
}

insertAtEnd(&result, sub);

if (list1 != NULL) {
list1 = list1->next;
}
if (list2 != NULL) {
list2 = list2->next;
}
}

result = reverseList(result);

while (result != NULL && result->data == 0) {


Node* temp = result;
result = result->next;
free(temp);
}

return result;
}

void displayList(Node* head) {


Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* list1 = NULL;
Node* list2 = NULL;

insertAtEnd(&list1, 7);
insertAtEnd(&list1, 9);
insertAtEnd(&list1, 8);

insertAtEnd(&list2, 5);
insertAtEnd(&list2, 4);
insertAtEnd(&list2, 1);

printf("List 1: ");
displayList(list1);
printf("List 2: ");
displayList(list2);

Node* result = subtractLists(list1, list2);

printf("Subtraction Result: ");


displayList(result);

return 0;
}
/*OUTPUT:-
List 1: 7 9 8
List 2: 5 4 1
*/

/*Q5.Write a C program to craeate a single linked list , like L0


-> L1 -> … -> Ln-1 -> Ln. Write another C
fucntion to rearrange the nodes in the list so that the new
formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2
-> Ln-2 .You are required to do this in place without altering
the nodes’ values.*/

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

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

typedef struct Node Node;

Node* createNode(int data) {


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

void insertAtEnd(Node** head, int data) {


Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

Node* reverseList(Node* head) {


Node *prev, *current, *next;
prev = NULL;
current = head;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}

void rearrangeList(Node** head) {


if (*head == NULL || (*head)->next == NULL) {
return;
}

// Finding the midpoint of the linked list


Node *slowPtr = *head, *fastPtr = *head;
while (fastPtr != NULL && fastPtr->next != NULL) {
slowPtr = slowPtr->next;
fastPtr = fastPtr->next->next;
}

// Reversing the second half of the linked list starting


from the midpoint
Node* secondHalf = reverseList(slowPtr);

// Merging the first half and the reversed second half


alternately
Node* current = *head;
while (secondHalf->next != NULL) {
Node* temp = current->next;
current->next = secondHalf;
current = temp;

temp = secondHalf->next;
secondHalf->next = current;
secondHalf = temp;
}
}

// Function to display the contents of a linked list


void displayList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* head = NULL;

// Create a sample linked list


insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtEnd(&head, 4);
insertAtEnd(&head, 5);

printf("Original List: ");


displayList(head);

// Rearrange the linked list as specified


rearrangeList(&head);

printf("Rearranged List: ");


displayList(head);

return 0;
}
/*OUTPUT:-
Original List: 1 2 3 4 5
Rearranged List: 1 5 2 4 3
*/

/*Q6.Write a C program to create two link lists positive and


negative from Original linked list, so that
positive linked list contains all positive elements and
negative linked list contains negative elements.
Positive and negative linked lists should use the node of
existing original linked list.*/

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

// Node structure for Linked List


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

typedef struct Node 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 a linked list


void insertAtEnd(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

// Function to remove a node from a linked list by its address


void removeNode(Node** head, Node* nodeToRemove) {
if (*head == NULL || nodeToRemove == NULL) {
return;
}

if (*head == nodeToRemove) {
*head = nodeToRemove->next;
free(nodeToRemove);
return;
}

Node* current = *head;


while (current->next != NULL && current->next !=
nodeToRemove) {
current = current->next;
}

if (current->next == NULL) {
return;
}

current->next = nodeToRemove->next;
free(nodeToRemove);
}

// Function to split the original linked list into positive and


negative linked lists
void splitLists(Node* original, Node** positive, Node**
negative) {
Node* current = original;
while (current != NULL) {
if (current->data >= 0) {
insertAtEnd(positive, current->data);
removeNode(&original, current);
} else {
insertAtEnd(negative, current->data);
removeNode(&original, current);
}
current = original;
}
}

// Function to display the contents of a linked list


void displayList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
Node* original = NULL;

// Create a sample linked list


insertAtEnd(&original, -3);
insertAtEnd(&original, 5);
insertAtEnd(&original, -9);
insertAtEnd(&original, 7);
insertAtEnd(&original, 11);
insertAtEnd(&original, -2);

printf("Original List: ");


displayList(original);

Node* positive = NULL;


Node* negative = NULL;

// Split the original linked list into positive and negative


linked lists
splitLists(original, &positive, &negative);

printf("Positive List: ");


displayList(positive);

printf("Negative List: ");


displayList(negative);

return 0;
}
/*OUTPUT:-
Original List: -3 5 -9 7 11 -2
Positive List: 5 7 11
Negative List: -3 -9 -2
*/

/*Q7.W.A.P. to create a binary search tree and perform following


operations:
1) Search a particular key.
2) Delete a node from the tree.
3) Find total number of leaf nodes
4) Find height of a binary search tree
5) Count total numbers of nodes from right hand side of root
node
6) K
th largest element without doing any modification in Binary
Search Tree*/

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

// Node structure for Binary Search Tree


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

typedef struct Node Node;

// Function to create a new node


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

// Function to insert a node into the Binary Search Tree


Node* insert(Node* 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;
}

// Function to search for a key in the Binary Search Tree


Node* search(Node* root, int key) {
if (root == NULL || root->data == key) {
return root;
}

if (key < root->data) {


return search(root->left, key);
}

return search(root->right, key);


}

// Function to find the minimum value node in a subtree


Node* findMin(Node* node) {
Node* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}

// Function to delete a node from the Binary Search Tree


Node* deleteNode(Node* root, int key) {
if (root == NULL) {
return root;
}

if (key < root->data) {


root->left = deleteNode(root->left, key);
} else if (key > root->data) {
root->right = deleteNode(root->right, key);
} else {
// Node to delete found with one child or no child
if (root->left == NULL) {
Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
Node* temp = root->left;
free(root);
return temp;
}

// Node to delete found with two children


Node* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}

// Function to count the number of leaf nodes in a BST


int countLeafNodes(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 calculate the height of a BST


int getHeight(Node* root) {
if (root == NULL) {
return 0;
}

int leftHeight = getHeight(root->left);


int rightHeight = getHeight(root->right);

return (leftHeight > rightHeight) ? (leftHeight + 1) :


(rightHeight + 1);
}

// Function to count nodes from right side of the root node


int countNodesFromRight(Node* root) {
if (root == NULL) {
return 0;
}

if (root->right != NULL) {
return 1 + countNodesFromRight(root->right);
}

return countNodesFromRight(root->left);
}

// Global variable to store the Kth largest element


int KthLargest = 0;

// Function to find the Kth largest element in the BST


void kthLargestUtil(Node* root, int k, int* count) {
if (root == NULL || *count >= k) {
return;
}

kthLargestUtil(root->right, k, count);

(*count)++;
if (*count == k) {
KthLargest = root->data;
return;
}

kthLargestUtil(root->left, k, count);
}

// Function to find the Kth largest element without modifying


the BST
int findKthLargest(Node* root, int k) {
int count = 0;
kthLargestUtil(root, k, &count);
return KthLargest;
}

int main() {
Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// 1) Search a particular key


int keyToSearch = 40;
Node* searchResult = search(root, keyToSearch);
if (searchResult != NULL) {
printf("Key %d found in the tree\n", keyToSearch);
} else {
printf("Key %d not found in the tree\n");
}

return 0;
}
/*OUTPUT:-
Key 40 found in the tree
*/
/*Q8.Write a program to add of two polynomials of degree n,
using linked list
For example p1=anx
n+an-1x
n-1 + an-2x
n-2 + …….. a0x
0
P2=bnx
n+bn-1x
n-1 + bn-2x
n-2 + …….. b0x
0
p1 = first polynomial
p2 = second polynomial
Find out p3= p1+p2*/

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

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

typedef struct Node Node;

Node* createNode(int coeff, int exp) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->coefficient = coeff;
newNode->exponent = exp;
newNode->next = NULL;
return newNode;
}

void addTerm(Node** head, int coeff, int exp) {


Node* newTerm = createNode(coeff, exp);

if (*head == NULL) {
*head = newTerm;
return;
}

Node* current = *head;


while (current->next != NULL) {
current = current->next;
}
current->next = newTerm;
}

void display(Node* head) {


if (head == NULL) {
printf("Empty polynomial\n");
return;
}

while (head != NULL) {


printf("%dx^%d ", head->coefficient, head->exponent);
if (head->next != NULL) {
printf("+ ");
}
head = head->next;
}
printf("\n");
}

Node* addPolynomials(Node* p1, Node* p2) {


Node* result = NULL;
Node* current1 = p1;
Node* current2 = p2;

while (current1 != NULL || current2 != NULL) {


if (current1 == NULL) {
while (current2 != NULL) {
addTerm(&result, current2->coefficient,
current2->exponent);
current2 = current2->next;
}
break;
} else if (current2 == NULL) {
while (current1 != NULL) {
addTerm(&result, current1->coefficient,
current1->exponent);
current1 = current1->next;
}
break;
} else {
if (current1->exponent == current2->exponent) {
addTerm(&result, current1->coefficient +
current2->coefficient, current1->exponent);
current1 = current1->next;
current2 = current2->next;
} else if (current1->exponent > current2->exponent)
{
addTerm(&result, current1->coefficient,
current1->exponent);
current1 = current1->next;
} else {
addTerm(&result, current2->coefficient,
current2->exponent);
current2 = current2->next;
}
}
}

return result;
}

int main() {
Node* p1 = NULL;
addTerm(&p1, 3, 2);
addTerm(&p1, 2, 1);
addTerm(&p1, 5, 0);

Node* p2 = NULL;
addTerm(&p2, 4, 3);
addTerm(&p2, 1, 1);
addTerm(&p2, 2, 0);

Node* p3 = addPolynomials(p1, p2);

printf("p1: ");
display(p1);
printf("p2: ");
display(p2);
printf("p3: ");
display(p3);

return 0;
}
/*OUTPUT:-
p1: 3x^2 + 2x^1 + 5x^0
p2: 4x^3 + 1x^1 + 2x^0
p3: 4x^3 + 3x^2 + 3x^1 + 7x^0
*/

/*Q9.Write a C program to sort a sequence of characters given by


user in an array, using Quick sort
technique.
*/
#include <stdio.h>

void swap(char* a, char* b) {


char temp = *a;
*a = *b;
*b = temp;
}

int partition(char arr[], int low, int high) {


char pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(char arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


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

int main() {
int size;

printf("Enter the number of characters in the sequence: ");


scanf("%d", &size);

char sequence[size];

printf("Enter the characters: ");


for (int i = 0; i < size; i++) {
scanf(" %c", &sequence[i]);
}

quickSort(sequence, 0, size - 1);

printf("Sorted sequence: ");


for (int i = 0; i < size; i++) {
printf("%c ", sequence[i]);
}
printf("\n");

return 0;
}
/*OUTPUT:-
Enter the number of characters in the sequence: 5
Enter the characters: 9
8
2
4
1
Sorted sequence: 1 2 4 8 9 */
/*Q10.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.*/

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

struct Process {
int processID;
int remainingTime;
struct Process* next;
};

typedef struct Process Process;

Process* createProcess(int processID, int remainingTime) {


Process* newProcess = (Process*)malloc(sizeof(Process));
newProcess->processID = processID;
newProcess->remainingTime = remainingTime;
newProcess->next = NULL;
return newProcess;
}

void insertProcess(Process** head, int processID, int


remainingTime) {
Process* newProcess = createProcess(processID,
remainingTime);

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

void timeSharing(Process** head, int timeSlot) {


if (*head == NULL) {
printf("No processes in the list.\n");
return;
}

Process* current = *head;


printf("Processes execution order:\n");
do {
printf("Time slot %d - Process %d\n", timeSlot, current-
>processID);

if (current->remainingTime > timeSlot) {


current->remainingTime -= timeSlot;
current = current->next;
} else {
timeSlot -= current->remainingTime;
printf("Process %d completed in total time %d\n",
current->processID, timeSlot);
Process* temp = current->next;

// Remove the completed process from the list


if (current == *head) {
Process* tail = *head;
while (tail->next != *head) {
tail = tail->next;
}
*head = temp;
tail->next = temp;
} else {
Process* prev = *head;
while (prev->next != current) {
prev = prev->next;
}
prev->next = temp;
}

free(current);
current = temp;
}
} while (current != *head);
}

int main() {
Process* processes = NULL;
int numProcesses, timeSlot;

printf("Enter the number of processes: ");


scanf("%d", &numProcesses);

printf("Enter time slot for each process: ");


scanf("%d", &timeSlot);

for (int i = 1; i <= numProcesses; i++) {


insertProcess(&processes, i, timeSlot);
}

timeSharing(&processes, timeSlot);
return 0;
}
/*OUTPUT:-
Enter the number of processes: 5
Enter time slot for each process: 10
Processes execution order:
Time slot 10 - Process 1
Process 1 completed in total time 0
*/

/*Q11.Write a C program to store the details of a directed


weighted graph (Use array of pointers concept).*/

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

// Structure to represent an edge in the graph


struct Edge {
int dest;
int weight;
struct Edge* next;
};

typedef struct Edge Edge;

// Structure to represent a vertex in the graph


struct Node {
int vertex;
Edge* edges; // Linked list of edges
};

typedef struct Node Node;

// Function to create a new edge


Edge* createEdge(int dest, int weight) {
Edge* newEdge = (Edge*)malloc(sizeof(Edge));
newEdge->dest = dest;
newEdge->weight = weight;
newEdge->next = NULL;
return newEdge;
}

// Function to create a new node (vertex) with an associated


linked list of edges
Node* createNode(int vertex) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->edges = NULL;
return newNode;
}
// Function to add an edge to a vertex in the graph
void addEdge(Node* graph[], int src, int dest, int weight) {
Edge* newEdge = createEdge(dest, weight);
newEdge->next = graph[src]->edges;
graph[src]->edges = newEdge;
}

// Function to display the graph


void displayGraph(Node* graph[], int vertices) {
for (int i = 0; i < vertices; i++) {
Edge* current = graph[i]->edges;
printf("Vertex %d -> ", graph[i]->vertex);
while (current != NULL) {
printf("(%d, w:%d) ", current->dest, current-
>weight);
current = current->next;
}
printf("\n");
}
}

int main() {

int vertices, edges;


printf("Enter the number of vertices in the graph: ");
scanf("%d", &vertices);

// Creating an array of pointers to Node to store the graph


Node* graph[vertices];

// Initialize each element of the graph array to a new node


for (int i = 0; i < vertices; i++) {
graph[i] = createNode(i);
}

printf("Enter the number of edges: ");


scanf("%d", &edges);

printf("Enter source, destination, and weight for each


edge:\n");
for (int i = 0; i < edges; i++) {
int src, dest, weight;
scanf("%d %d %d", &src, &dest, &weight);
if (src < 0 || src >= vertices || dest < 0 || dest >=
vertices) {
printf("Invalid edge.\n");
continue;
}
addEdge(graph, src, dest, weight);
}
printf("Graph representation:\n");
displayGraph(graph, vertices);

return 0;
}
/*OUTPUT:-
Enter the number of vertices in the graph: 4
Enter the number of edges: 5
Enter source, destination, and weight for each edge:
0 1 2
0 2 3
1 3 1
2 3 4
3 0 5
Graph representation:
Vertex 0 -> (2, w:3) (1, w:2)
Vertex 1 -> (3, w:1)
Vertex 2 -> (3, w:4)
Vertex 3 -> (0, w:5)
*/

/*Q12.Write a C program to implement BFS*/

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

// Structure to represent an edge in the graph


struct Edge {
int dest;
struct Edge* next;
};

typedef struct Edge Edge;

// Structure to represent a vertex in the graph


struct Node {
int vertex;
bool visited;
Edge* edges; // Linked list of edges
};

typedef struct Node Node;

// Structure to represent a queue for BFS


struct Queue {
int front, rear;
int capacity;
int* array;
};

typedef struct Queue Queue;

Queue* createQueue(int capacity) {


Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->capacity = capacity;
queue->front = queue->rear = -1;
queue->array = (int*)malloc(queue->capacity * sizeof(int));
return queue;
}

bool isQueueEmpty(Queue* queue) {


return (queue->front == -1);
}

void enqueue(Queue* queue, int item) {


if (queue->rear == queue->capacity - 1) {
printf("Queue overflow\n");
return;
}
if (queue->front == -1) {
queue->front = 0;
}
queue->rear++;
queue->array[queue->rear] = item;
}

int dequeue(Queue* queue) {


if (isQueueEmpty(queue)) {
printf("Queue underflow\n");
return -1;
}
int item = queue->array[queue->front];
if (queue->front == queue->rear) {
queue->front = queue->rear = -1;
} else {
queue->front++;
}
return item;
}

// Function to create a new edge


Edge* createEdge(int dest) {
Edge* newEdge = (Edge*)malloc(sizeof(Edge));
newEdge->dest = dest;
newEdge->next = NULL;
return newEdge;
}
// Function to create a new node (vertex) with an associated
linked list of edges
Node* createNode(int vertex) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->visited = false;
newNode->edges = NULL;
return newNode;
}

// Function to add an edge to a vertex in the graph


void addEdge(Node* graph[], int src, int dest) {
Edge* newEdge = createEdge(dest);
newEdge->next = graph[src]->edges;
graph[src]->edges = newEdge;
}

// Function to perform Breadth-First Search


void BFS(Node* graph[], int startVertex, int numVertices) {
Queue* queue = createQueue(numVertices);
graph[startVertex]->visited = true;
enqueue(queue, startVertex);

printf("BFS Traversal starting from vertex %d: ",


startVertex);

while (!isQueueEmpty(queue)) {
int currentVertex = dequeue(queue);
printf("%d ", currentVertex);

Edge* currentEdge = graph[currentVertex]->edges;


while (currentEdge != NULL) {
int destVertex = currentEdge->dest;
if (!graph[destVertex]->visited) {
graph[destVertex]->visited = true;
enqueue(queue, destVertex);
}
currentEdge = currentEdge->next;
}
}
printf("\n");
}

int main() {
int numVertices, numEdges, startVertex;

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


scanf("%d", &numVertices);

Node* graph[numVertices];
for (int i = 0; i < numVertices; i++) {
graph[i] = createNode(i);
}

printf("Enter the number of edges: ");


scanf("%d", &numEdges);

printf("Enter source and destination for each edge:\n");


for (int i = 0; i < numEdges; i++) {
int src, dest;
scanf("%d %d", &src, &dest);
if (src < 0 || src >= numVertices || dest < 0 || dest >=
numVertices) {
printf("Invalid edge.\n");
continue;
}
addEdge(graph, src, dest);
}

printf("Enter the starting vertex for BFS: ");


scanf("%d", &startVertex);
if (startVertex < 0 || startVertex >= numVertices) {
printf("Invalid start vertex.\n");
return 1;
}

BFS(graph, startVertex, numVertices);

return 0;
}
/*OUTPUT:-
Enter the number of vertices: 6
Enter the number of edges: 8
Enter source and destination for each edge:
0 1
0 2
1 3
1 4
2 5
2 6
3 7
4 7
Enter the starting vertex for BFS: 0
BFS Traversal starting from vertex 0: 0 1 2 3 4 5 6 7

*/

You might also like