Thursday, July 25, 2024

Graph Traversal - BFS

Write a C program for finding the Breadth First Search of a graph.

// C program for finding the Breadth First Search of a graph 

#include <stdio.h>

#include <stdlib.h>


#define MAX_VERTICES 100


// Function to add an edge to the graph

void addEdge(int graph[MAX_VERTICES][MAX_VERTICES], int start, int end) {

    graph[start][end] = 1;

    graph[end][start] = 1; // For undirected graph

}


// Function to perform BFS traversal

void BFS(int graph[MAX_VERTICES][MAX_VERTICES], int vertices, int startVertex) {

    int visited[MAX_VERTICES] = {0}; // Initialize all vertices as not visited

    int queue[MAX_VERTICES];

    int front = -1, rear = -1,i;


    // Mark the startVertex as visited and enqueue it

    visited[startVertex] = 1;

    queue[++rear] = startVertex;


    printf("BFS Traversal Order: ");


    while (front != rear) {

        int currentVertex = queue[++front];

        printf(" %d --> ", currentVertex);


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

            if (graph[currentVertex][i] == 1 && !visited[i]) {

                visited[i] = 1;

                queue[++rear] = i;

            }

        }

    }


    printf("\n");

}


// Function to print the adjacency matrix

void printAdjacencyMatrix(int graph[MAX_VERTICES][MAX_VERTICES], int vertices) {

    int i, j;

    printf("Adjacency Matrix:\n");

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

        for (j = 0; j < vertices; j++) {

            printf("%d ", graph[i][j]);

        }

        printf("\n");

    }

}


int main() {

    int vertices, edges,i;

    printf("\n****Breadth-First Search (BFS) traversal****\n");

    printf("-----------------------------------------------\n");


    // Input the number of vertices

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

    scanf("%d",&vertices);


    if (vertices <= 0 || vertices > MAX_VERTICES) {

        printf("Invalid number of vertices. Exiting...\n");

        return 1;

    }


    int graph[MAX_VERTICES][MAX_VERTICES] = {0}; // Initialize the adjacency matrix with zeros


    // Input the number of edges

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

    scanf("%d",&edges);


    if (edges < 0 || edges > vertices * (vertices - 1) / 2) {

        printf("Invalid number of edges. Exiting...\n");

        return 1;

    }


    // Input edges and construct the adjacency matrix

    for (i = 0; i < edges; i++) {

        int start, end;

        printf("Input edge %d (start end): ", i + 1);

        scanf("%d %d", &start, &end);


        // Validate input vertices

        if (start < 0 || start >= vertices || end < 0 || end >= vertices) {

            printf("Invalid vertices. Try again.\n");

            i--;

            continue;

        }


        addEdge(graph, start, end);

    }


    // Print the adjacency matrix

    printAdjacencyMatrix(graph, vertices);


    // Input the starting vertex for BFS traversal

    int startVertex;

    printf("Input the starting vertex for BFS traversal: ");

    scanf("%d", &startVertex);


    if (startVertex < 0 || startVertex >= vertices) {

        printf("Invalid starting vertex. Exiting...\n");

        return 1;

    }


    // Perform BFS traversal

    BFS(graph, vertices, startVertex);


    return 0;

}

Input/Output:

****Breadth-First Search (BFS) traversal****
-----------------------------------------------
Input the number of vertices: 7
Input the number of edges: 11
Input edge 1 (start end): 0 1
Input edge 2 (start end): 0 3
Input edge 3 (start end): 0 4
Input edge 4 (start end): 3 4
Input edge 5 (start end): 1 4
Input edge 6 (start end): 1 2
Input edge 7 (start end): 4 2
Input edge 8 (start end): 4 5
Input edge 9 (start end): 2 5
Input edge 10 (start end): 2 6
Input edge 11 (start end): 5 6
Adjacency Matrix:
0 1 0 1 1 0 0
1 0 1 0 1 0 0
0 1 0 0 1 1 1
1 0 0 0 1 0 0
1 1 1 1 0 1 0
0 0 1 0 1 0 1
0 0 1 0 0 1 0
Input the starting vertex for BFS traversal: 0
BFS Traversal Order:  0 -->  1 -->  3 -->  4 -->  2 -->  5 -->  6 -->

--------------------------------
Process exited after 49.83 seconds with return value 0
Press any key to continue . . .




Wednesday, July 24, 2024

Graph Traversal - DFS

Write a C program for finding the Depth First Search of a graph.

//C program for finding the Depth First Search of a graph. 

#include <stdio.h>

#define MAX_VERTICES 100

// Function to perform Depth-First Search (DFS) traversal

void DFS(int graph[MAX_VERTICES][MAX_VERTICES], int visited[MAX_VERTICES], int vertices, int start) {

    int i;

    printf(" %d --> ", start); // Print the current vertex

    visited[start] = 1;    // Mark the current vertex as visited


    // Visit all adjacent vertices

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

        if (graph[start][i] == 1 && !visited[i]) {

            DFS(graph, visited, vertices, i);

        }

    }

}


// Function to print the adjacency matrix

void printAdjacencyMatrix(int graph[MAX_VERTICES][MAX_VERTICES], int vertices) {

    int i, j;

    printf("Adjacency Matrix:\n");

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

        for (j = 0; j < vertices; j++) {

            printf("%d ", graph[i][j]);

        }

        printf("\n");

    }

}


int main() {

    int vertices, edges, i, j;

    printf("\n****Depth-First Search (DFS) traversal****\n");

    printf("-----------------------------------------------\n");


    // Input the number of vertices

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

    scanf("%d", &vertices);


    if (vertices <= 0 || vertices > MAX_VERTICES) {

        printf("Invalid number of vertices. Exiting...\n");

        return 1;

    }


    int graph[MAX_VERTICES][MAX_VERTICES] = {0}; // Initialize the adjacency matrix with zeros

    int visited[MAX_VERTICES] = {0};             // Initialize the visited array with zeros


    // Input the number of edges

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

    scanf("%d", &edges);


    if (edges < 0 || edges > vertices * (vertices - 1)) {

        printf("Invalid number of edges. Exiting...\n");

        return 1;

    }


    // Input edges and construct the adjacency matrix

    for (i = 0; i < edges; i++) {

        int start, end;

        printf("Enter edge %d (start end): ", i + 1);

        scanf("%d %d", &start, &end);


        // Validate input vertices

        if (start < 0 || start >= vertices || end < 0 || end >= vertices) {

            printf("Invalid vertices. Try again.\n");

            i--;

            continue;

        }


        graph[start][end] = 1;

        // For directed graph, comment the following line:

        graph[end][start] = 1;

    }


    // Print the adjacency matrix

    printAdjacencyMatrix(graph, vertices);


    // Input the starting vertex for DFS traversal

    int startVertex;

    printf("Enter the starting vertex for DFS traversal: ");

    scanf("%d", &startVertex);


    if (startVertex < 0 || startVertex >= vertices) {

        printf("Invalid starting vertex. Exiting...\n");

        return 1;

    }


    printf("DFS Traversal Order: ");

    DFS(graph, visited, vertices, startVertex);


    return 0;

}

Input/Output:






Friday, July 19, 2024

Dijkstra's algorithm(single-source shortest path problem)-Source Code in C

Write a C program for finding the shortest path from a given source to any vertex in a digraph using Dijkstra’s algorithm. 

/*This program prompts the user to input the number of vertices, edges, and the cost of each edge. 

It then prints the adjacency matrix and calculates the shortest path from the source vertex to all other vertices using Dijkstra's algorithm.*/

#include <stdio.h>

#include <limits.h>


#define NO_EDGE -1


void printGraph(int graph[][50], int V) {

    int i, j;

    printf("\nThe adjacency matrix is:\n");

    for (i = 0; i < V; i++) {

        for (j = 0; j < V; j++) {

            if (graph[i][j] == NO_EDGE)

                printf("%4d ", 0);

            else

                printf("%4d ", graph[i][j]);

        }

        printf("\n");

    }

}


int minDistance(int dist[], int sptSet[], int V) {

    int min = INT_MAX, min_index;

    int vertex;

    for (vertex = 0; vertex < V; vertex++) {

        if (sptSet[vertex] == 0 && dist[vertex] <= min) {

            min = dist[vertex];

            min_index = vertex;

        }

    }

    return min_index;

}


void printPath(int parent[], int j) {

    if (parent[j] == -1)

        return;

    printPath(parent, parent[j]);

    printf(" -> %d", j + 1); // Adjusting to one-based index for output

}

void drawGraph(int graph[][50], int V) {

    int i, j;


    printf("\nGraph representation (nodes and edges):\n");

    for (i = 0; i < V; i++) {

        printf("Node %d:\n", i + 1);

        for (j = 0; j < V; j++) {

            if (graph[i][j] != NO_EDGE) {

                printf("  -> Node %d (Cost: %d)\n", j + 1, graph[i][j]);

            }

        }

    }

}

void printSolution(int dist[], int parent[], int V, int src) {

    int i;

    printf("Vertex\t Distance\tPath");

    for (i = 0; i < V; i++) {

        printf("\n%d -> %d \t\t %d\t\t%d", src + 1, i + 1, dist[i], src + 1); // Adjusting to one-based index for output

        printPath(parent, i);

    }

    printf("\n");

}


void dijkstra(int graph[][50], int src, int V) {

    int dist[50];

    int sptSet[50];

    int parent[50];

    int i, count, vertex;


    for (i = 0; i < V; i++) {

        dist[i] = INT_MAX;

        sptSet[i] = 0;

        parent[i] = -1;

    }


    dist[src] = 0;


    for (count = 0; count < V - 1; count++) {

        int u = minDistance(dist, sptSet, V);

        sptSet[u] = 1;


        for (vertex = 0; vertex < V; vertex++) {

            if (!sptSet[vertex] && graph[u][vertex] != NO_EDGE && dist[u] != INT_MAX && dist[u] + graph[u][vertex] < dist[vertex]) {

                dist[vertex] = dist[u] + graph[u][vertex];

                parent[vertex] = u;

            }

        }

    }


    printSolution(dist, parent, V, src);

}


int main() {

    int V, E, i, j;

    printf("****Dijkstra\'s algorithm(single-source shortest path problem)*****\n");

    printf("------------------------------------------------------------------\n");

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

    scanf("%d", &V);


    int graph[50][50];

    for (i = 0; i < V; i++) {

        for (j = 0; j < V; j++) {

            graph[i][j] = NO_EDGE;

        }

    }


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

    scanf("%d", &E);


    printf("Enter the end vertices of each edge and its cost (one-based index):\n");

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

        int u, v, cost;

        printf("Edge %d: ", i + 1);

        scanf("%d %d %d", &u, &v, &cost);

        graph[u - 1][v - 1] = cost; // Adjusting to zero-based index

    }


    printGraph(graph, V);

    drawGraph(graph, V);



    int src;

    printf("\nEnter the source vertex (one-based index): ");

    scanf("%d", &src);


    dijkstra(graph, src - 1, V); // Adjusting to zero-based index


    return 0;

}

INPUT/OUTPUT

Testcase1: for the graph


****Dijkstra's algorithm(single-source shortest path problem)*****

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

Enter the number of vertices: 6

Enter the number of edges: 9

Enter the end vertices of each edge and its cost (one-based index):

Edge 1: 1 2 4

Edge 2: 1 3 5

Edge 3: 2 3 11

Edge 4: 2 4 9

Edge 5: 2 5 7

Edge 6: 3 5 3

Edge 7: 4 5 13

Edge 8: 4 6 2

Edge 9: 5 6 6

 

The adjacency matrix is:

   0    4    5    0    0    0

   0    0   11    9    7    0

   0    0    0    0    3    0

   0    0    0    0   13    2

   0    0    0    0    0    6

   0    0    0    0    0    0

 

Graph representation (nodes and edges):

Node 1:

  -> Node 2 (Cost: 4)

  -> Node 3 (Cost: 5)

Node 2:

  -> Node 3 (Cost: 11)

  -> Node 4 (Cost: 9)

  -> Node 5 (Cost: 7)

Node 3:

  -> Node 5 (Cost: 3)

Node 4:

  -> Node 5 (Cost: 13)

  -> Node 6 (Cost: 2)

Node 5:

  -> Node 6 (Cost: 6)

Node 6:

 

Enter the source vertex (one-based index): 1

Vertex   Distance       Path

1 -> 1           0              1

1 -> 2           4              1 -> 2

1 -> 3           5              1 -> 3

1 -> 4           13             1 -> 2 -> 4

1 -> 5           8              1 -> 3 -> 5

1 -> 6           14             1 -> 3 -> 5 -> 6

 

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

Process exited after 114.5 seconds with return value 0

Press any key to continue . . .

Testcase2: for the graph







****Dijkstra's algorithm(single-source shortest path problem)*****

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

Enter the number of vertices: 9

Enter the number of edges: 14

Enter the end vertices of each edge and its cost (one-based index):

Edge 1: 1 2 4

Edge 2: 1 8 8

Edge 3: 2 8 11

Edge 4: 2 3 8

Edge 5: 8 9 7

Edge 6: 8 7 1

Edge 7: 3 9 2

Edge 8: 9 7 6

Edge 9: 7 6 2

Edge 10: 3 6 4

Edge 11: 3 4 7

Edge 12: 4 6 14

Edge 13: 6 5 10

Edge 14: 4 5 9


The adjacency matrix is:

   0    4    0    0    0    0    0    8    0

   0    0    8    0    0    0    0   11    0

   0    0    0    7    0    4    0    0    2

   0    0    0    0    9   14    0    0    0

   0    0    0    0    0    0    0    0    0

   0    0    0    0   10    0    0    0    0

   0    0    0    0    0    2    0    0    0

   0    0    0    0    0    0    1    0    7

   0    0    0    0    0    0    6    0    0


Graph representation (nodes and edges):

Node 1:

  -> Node 2 (Cost: 4)

  -> Node 8 (Cost: 8)

Node 2:

  -> Node 3 (Cost: 8)

  -> Node 8 (Cost: 11)

Node 3:

  -> Node 4 (Cost: 7)

  -> Node 6 (Cost: 4)

  -> Node 9 (Cost: 2)

Node 4:

  -> Node 5 (Cost: 9)

  -> Node 6 (Cost: 14)

Node 5:

Node 6:

  -> Node 5 (Cost: 10)

Node 7:

  -> Node 6 (Cost: 2)

Node 8:

  -> Node 7 (Cost: 1)

  -> Node 9 (Cost: 7)

Node 9:

  -> Node 7 (Cost: 6)


Enter the source vertex (one-based index): 1

Vertex   Distance       Path

1 -> 1           0              1

1 -> 2           4              1 -> 2

1 -> 3           12             1 -> 2 -> 3

1 -> 4           19             1 -> 2 -> 3 -> 4

1 -> 5           21             1 -> 8 -> 7 -> 6 -> 5

1 -> 6           11             1 -> 8 -> 7 -> 6

1 -> 7           9              1 -> 8 -> 7

1 -> 8           8              1 -> 8

1 -> 9           14             1 -> 2 -> 3 -> 9


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

Process exited after 191.6 seconds with return value 0

Press any key to continue . . .


Tuesday, July 16, 2024

Warshall’s Algorithm to find Transitive Closure

What is the Transitive Closure of a Graph?

The transitive closure of a graph is a data structure that represents all the shortest paths between the nodes of the graph. More specifically, given a directed graph G = (V, E), the transitive closure is a new graph G' = (V, E'), where there is an edge (u, v) in E' if there is a path from u to v in G. In other words, the transitive closure of a graph is a compact representation of all the reachability information in the graph.

There are different methods to compute the transitive closure of a graph, including the Floyd-Warshall algorithm, the dynamic programming approach, and the matrix multiplication method. The choice of the method depends on the specific problem and the properties of the graph.

Real-World Examples of Transitive Closure

The concept of transitive closure can be applied to various real-world scenarios, such as:

Social Networks: In a social network like Facebook or LinkedIn, users are connected through friendships or professional connections. The transitive closure of the social network graph can be used to analyze the reachability between users and find the shortest path between them.

Web Crawling: Search engines like Google use web crawlers to index websites. The transitive closure of the web graph can be used to determine the reachability between different web pages and prioritize the crawling process.

Transportation Networks: In a transportation network, cities or stations are connected through roads, railways, or air routes. The transitive closure of the transportation network graph can be used to compute the shortest paths between cities or stations, which is essential for route planning and optimization.

Dependency Management: In software development, modules or packages often depend on other modules or packages. The transitive closure of the dependency graph can be used to determine the full set of dependencies for a given module or package, which is important for software building and distribution.

SOURCE CODE in C

/*This is a C Program to find Transitive Closure of a Digraph using Warshall’s Algorithm*/

#include<stdio.h>

#include<conio.h>

#include<math.h>

int max(int,int);

void warshal(int p[10][10],int n) {

    int i,j,k;

    for(k=1;k<=n;k++)

        for(i=1;i<=n;i++)

            for(j=1;j<=n;j++)

                p[i][j]=max(p[i][j],p[i][k]&&p[k][j]);

}

int max(int a,int b) {

    if(a>b)

        return(a);

    else

        return(b);

}

void main() {

    int p[10][10]={0},n,e,u,v,i,j;

    printf("****Transitive Closure of a Digraph using Warshall’s Algorithm*****\n\n");

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

    scanf("%d",&n);

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

    scanf("%d",&e);

    for(i=1;i<=e;i++) {

        printf("Enter the end vertices of edge %d:",i);

        scanf("%d%d",&u,&v);

        p[u][v]=1;

    }

    printf("\n Adjacency Matrix of input data: \n");

    for(i=1;i<=n;i++) {

        for(j=1;j<=n;j++)

            printf("%d\t",p[i][j]);

        printf("\n");

    }

    

warshal(p,n);

    

    printf("\n Transitive closure: \n");

    for(i=1;i<=n;i++) {

        for(j=1;j<=n;j++)

            printf("%d\t",p[i][j]);

        printf("\n");

    }

}

 INPUT/ OUTPUT:



****Transitive Closure of a Digraph using WarshallÆs Algorithm*****


Enter the number of vertices:4

Enter the number of edges:4

Enter the end vertices of edge 1:1 2

Enter the end vertices of edge 2:2 4

Enter the end vertices of edge 3:4 1

Enter the end vertices of edge 4:4 3


 Adjacency Matrix of input data:

0       1       0       0

0       0       0       1

0       0       0       0

1       0       1       0


 Transitive closure:

1       1       1       1

1       1       1       1

0       0       0       0

1       1       1       1


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

Process exited after 94.09 seconds with return value 4

Press any key to continue . . .


Monday, July 8, 2024

 C program to create a binary search tree and for implementing the in order, Pre order, post order traversal using recursion

Source Code in C:

//program that will create a binary search tree and travese it in inorder, preoreder and postorder.

#include <stdio.h>

#include <stdlib.h>

struct tnode

{

    int data;

    struct tnode *right;

    struct tnode *left;

};


struct tnode *CreateBST(struct tnode *, int);

void Inorder(struct tnode *);

void Preorder(struct tnode *);

void Postorder(struct tnode *);


int main()

{

    struct tnode *root = NULL;

    int choice, item, n, i;

    do

    {

        printf("\n\n****Binary Search Tree Operations****");

        printf("\n1. Creation of BST");

        printf("\n2. Traverse in Inorder");

        printf("\n3. Traverse in Preorder");

        printf("\n4. Traverse in Postorder");

        printf("\n5. Exit");

        printf("\nEnter Choice : ");

        scanf("%d",&choice);

        switch(choice)

        {

        case 1:

            root = NULL;

            printf("\nBST for How Many Nodes ? ");

            scanf("%d",&n);

            for(i = 1; i <= n; i++)

            {

                printf("Enter data for node %d : ", i);

                scanf("%d",&item);

                root = CreateBST(root,item);

            }

            printf("\nBST with %d nodes is ready to Use!!", n);

            break;

        case 2:

            printf("\nBST Traversal in INORDER:");

            Inorder(root);

            break;

        case 3:

            printf("\nBST Traversal in PREORDER:");

            Preorder(root);

            break;

        case 4:

            printf("\nBST Traversal in POSTORDER:");

            Postorder(root);

            break;

        case 5:

            printf("\nTerminating");

            break;

        default:

            printf("\nInvalid Option !!! Try Again !!");

            break;

        }

    } while(choice != 5);

    return 0;

}


struct tnode* CreateBST(struct tnode *root, int item)

{

    if(root == NULL)

    {

        root = (struct tnode *)malloc(sizeof(struct tnode));

        root->left = root->right = NULL;

        root->data = item;

        return root;

    }

    else

    {

        if(item < root->data )

            root->left = CreateBST(root->left,item);

        else if(item > root->data )

            root->right = CreateBST(root->right,item);

        else

            printf(" Duplicate Element !! Not Allowed !!!");


        return(root);

    }

}


void Inorder(struct tnode *root)

{

    if( root != NULL)

    {

        Inorder(root->left);

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

        Inorder(root->right);

    }

}


void Preorder(struct tnode *root)

{

    if( root != NULL)

    {

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

        Preorder(root->left);

        Preorder(root->right);

    }

}


void Postorder(struct tnode *root)

{

    if( root != NULL)

    {

        Postorder(root->left);

        Postorder(root->right);

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

    }

}

Input/Output:



****Binary Search Tree Operations****
1. Creation of BST
2. Traverse in Inorder
3. Traverse in Preorder
4. Traverse in Postorder
5. Exit
Enter Choice : 1

BST for How Many Nodes ? 9
Enter data for node 1 : 56
Enter data for node 2 : 34
Enter data for node 3 : 23
Enter data for node 4 : 67
Enter data for node 5 : 2
Enter data for node 6 : -11
Enter data for node 7 : 77
Enter data for node 8 : 89
Enter data for node 9 : -45

BST with 9 nodes is ready to Use!!

****Binary Search Tree Operations****
1. Creation of BST
2. Traverse in Inorder
3. Traverse in Preorder
4. Traverse in Postorder
5. Exit
Enter Choice : 2

BST Traversal in INORDER: -45  -11  2  23  34  56  67  77  89

****Binary Search Tree Operations****
1. Creation of BST
2. Traverse in Inorder
3. Traverse in Preorder
4. Traverse in Postorder
5. Exit
Enter Choice : 3

BST Traversal in PREORDER: 56  34  23  2  -11  -45  67  77  89

****Binary Search Tree Operations****
1. Creation of BST
2. Traverse in Inorder
3. Traverse in Preorder
4. Traverse in Postorder
5. Exit
Enter Choice : 4

BST Traversal in POSTORDER: -45  -11  2  23  34  89  77  67  56

****Binary Search Tree Operations****
1. Creation of BST
2. Traverse in Inorder
3. Traverse in Preorder
4. Traverse in Postorder
5. Exit
Enter Choice : 4

BST Traversal in POSTORDER: -45  -11  2  23  34  89  77  67  56

****Binary Search Tree Operations****
1. Creation of BST
2. Traverse in Inorder
3. Traverse in Preorder
4. Traverse in Postorder
5. Exit
Enter Choice : 5

Terminating
--------------------------------
Process exited after 91.5 seconds with return value 0
Press any key to continue . . .

Tuesday, July 2, 2024

Representation of polynomials and the addition of two such polynomials using circular linked list: Source Code in C

C-program for the representation of polynomials using circular linked list and for the addition of two such polynomials.

/*This program covers the representation and addition of polynomials using circular linked lists, demonstrating dynamic memory allocation, circular linked list operations, and polynomial arithmetic.*/

#include <stdio.h>

#include <stdio.h>

#include <stdlib.h>


// Node structure for the circular 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 = newNode; // Pointing to itself for circular nature

    return newNode;

}


// Function to insert a node in the circular linked list

struct Node* insertNode(struct Node* head, int coefficient, int exponent) {

    struct Node* newNode = createNode(coefficient, exponent);


    if (head == NULL) {

        return newNode;

    } else {

        struct Node* temp = head;

        while (temp->next != head) {

            temp = temp->next;

        }

        temp->next = newNode;

        newNode->next = head;

    }

    return head;

}


// Function to display the polynomial in descending order of exponents

void displayPolynomial(struct Node* head) {

    if (head == NULL) {

        printf("0\n");

        return;

    }


    struct Node* temp = head;

    do {

        if (temp->coefficient != 0) {

            if (temp != head && temp->coefficient > 0) {

                printf(" + ");

            }

            printf("%dx^%d", temp->coefficient, temp->exponent);

        }

        temp = temp->next;

    } while (temp != head);

    printf("\n");

}


// Function to add two polynomials

struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) {

    struct Node* result = NULL;

    struct Node* temp1 = poly1;

    struct Node* temp2 = poly2;


    if (poly1 == NULL) return poly2;

    if (poly2 == NULL) return poly1;


    do {

        result = insertNode(result, temp1->coefficient, temp1->exponent);

        temp1 = temp1->next;

    } while (temp1 != poly1);


    do {

        struct Node* temp = result;

        int found = 0;

        do {

            if (temp->exponent == temp2->exponent) {

                temp->coefficient += temp2->coefficient;

                found = 1;

                break;

            }

            temp = temp->next;

        } while (temp != result);

        if (!found) {

            result = insertNode(result, temp2->coefficient, temp2->exponent);

        }

        temp2 = temp2->next;

    } while (temp2 != poly2);


    return result;

}


// Function to get polynomial input from the user in descending order of exponents

struct Node* inputPolynomial() {

    struct Node* poly = NULL;

    int coefficient, exponent, prevExponent = -1;

    char choice;


    do {

        int valid = 0;

        while (!valid) {

            printf("Enter coefficient: ");

            scanf("%d", &coefficient);

            printf("Enter exponent: ");

            scanf("%d", &exponent);

            if (prevExponent != -1 && exponent >= prevExponent) {

                printf("Error: Exponents must be entered in descending order.\n");

            } else {

                valid = 1;

            }

        }

        poly = insertNode(poly, coefficient, exponent);

        prevExponent = exponent;


        if (exponent == 0) {

            break;

        }


        printf("Do you want to add another term? (y/n): ");

        scanf(" %c", &choice);

    } while (choice == 'y' || choice == 'Y');


    return poly;

}


// Function to free the memory allocated for the polynomial

void freePolynomial(struct Node* head) {

    if (head == NULL) return;

    struct Node* temp = head;

    do {

        struct Node* next = temp->next;

        free(temp);

        temp = next;

    } while (temp != head);

}


int main() {

    struct Node* poly1 = NULL;

    struct Node* poly2 = NULL;

    struct Node* result = NULL;

    char choice;

    printf("****Representation and Addition of Polynomials using Circular Linked List****\n");

    printf("=============================================================================\n");

    do {

        printf("Enter the first polynomial:\n");

        poly1 = inputPolynomial();


        printf("\nEnter the second polynomial:\n");

        poly2 = inputPolynomial();


        printf("\nFirst Polynomial: ");

        displayPolynomial(poly1);


        printf("Second Polynomial: ");

        displayPolynomial(poly2);


        result = addPolynomials(poly1, poly2);


        printf("Resultant Polynomial after Addition: ");

        displayPolynomial(result);


        printf("\nDo you want to add another pair of polynomials? (y/n): ");

        scanf(" %c", &choice);


        // Free memory allocated for the polynomials to avoid memory leaks

        freePolynomial(poly1);

        freePolynomial(poly2);

        freePolynomial(result);


        poly1 = poly2 = result = NULL;

    } while (choice == 'y' || choice == 'Y');

    return 0;

}

Input/Output:👍


****Representation and Addition of Polynomials using Circular Linked List****

=============================================================================

Enter the first polynomial:

Enter coefficient: 7

Enter exponent: 4

Do you want to add another term? (y/n): y

Enter coefficient: -5

Enter exponent: 3

Do you want to add another term? (y/n): y

Enter coefficient: 6

Enter exponent: 2

Do you want to add another term? (y/n): y

Enter coefficient: -4

Enter exponent: 2

Error: Exponents must be entered in descending order.

Enter coefficient: -4

Enter exponent: 1

Do you want to add another term? (y/n): y

Enter coefficient: 2

Enter exponent: 0


Enter the second polynomial:

Enter coefficient: 9

Enter exponent: 4

Do you want to add another term? (y/n): y

Enter coefficient: -5

Enter exponent: 2

Do you want to add another term? (y/n): n


First Polynomial: 7x^4-5x^3 + 6x^2-4x^1 + 2x^0

Second Polynomial: 9x^4-5x^2

Resultant Polynomial after Addition: 16x^4-5x^3 + 1x^2-4x^1 + 2x^0


Do you want to add another pair of polynomials? (y/n): y

Enter the first polynomial:

Enter coefficient: 3

Enter exponent: 1

Do you want to add another term? (y/n): n


Enter the second polynomial:

Enter coefficient: 4

Enter exponent: 1

Do you want to add another term? (y/n): n


First Polynomial: 3x^1

Second Polynomial: 4x^1

Resultant Polynomial after Addition: 7x^1


Do you want to add another pair of polynomials? (y/n): n


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

Process exited after 191 seconds with return value 0

Press any key to continue . . .

Unit-1 Data Science Notes