0% found this document useful (0 votes)
5 views

Data Structure University Practicals 007.

Uploaded by

nalangillo
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Data Structure University Practicals 007.

Uploaded by

nalangillo
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 104

1.

Write a c program to implement circular queue ADT to do the insertion


and deletion operation

Program:

#include <stdio.h>

#include <stdlib.h>

#define SIZE 5 // Define the maximum size of the queue

Typedef struct {

Int items[SIZE];

Int front, rear;

} CircularQueue;

// Function to initialize the queue

Void initializeQueue(CircularQueue *q) {

q->front = -1;

q->rear = -1;

// Check if the queue is full

Int isFull(CircularQueue *q) {

Return (q->front == (q->rear + 1) % SIZE);

// Check if the queue is empty

Int isEmpty(CircularQueue *q) {

Return (q->front == -1);


}

// Insert an element into the queue

Void enqueue(CircularQueue *q, int value) {

If (isFull(q)) {

Printf(“Queue is full. Cannot insert %d\n”, value);

Return;

If (isEmpty(q)) {

q->front = 0;

q->rear = (q->rear + 1) % SIZE;

q->items[q->rear] = value;

printf(“Inserted %d into the queue.\n”, value);

// Remove an element from the queue

Int dequeue(CircularQueue *q) {

If (isEmpty(q)) {

Printf(“Queue is empty. Cannot dequeue.\n”);

Return -1;

Int value = q->items[q->front];

If (q->front == q->rear) { // If the queue becomes empty after this


operation

q->front = -1;

q->rear = -1;
} else {

q->front = (q->front + 1) % SIZE;

Printf(“Removed %d from the queue.\n”, value);

Return value;

// Display the elements of the queue

Void display(CircularQueue *q) {

If (isEmpty(q)) {

Printf(“Queue is empty.\n”);

Return;

Printf(“Queue elements are: “);

Int I = q->front;

While (1) {

Printf(“%d “, q->items[i]);

If (I == q->rear) break;

I = (I + 1) % SIZE;

Printf(“\n”);

// Main function to test the circular queue

Int main() {

CircularQueue q;

initializeQueue(&q);
enqueue(&q, 10);

enqueue(&q, 20);

enqueue(&q, 30);

enqueue(&q, 40);

enqueue(&q, 50);

display(&q);

dequeue(&q);

dequeue(&q);

display(&q);

enqueue(&q, 60);

enqueue(&q, 70);

display(&q);

return 0;

Output:

Inserted 10 into the queue.

Inserted 20 into the queue.


Inserted 30 into the queue.

Inserted 40 into the queue.

Inserted 50 into the queue.

Queue elements are: 10 20 30 40 50

Removed 10 from the queue.

Removed 20 from the queue.

Queue elements are: 30 40 50

Inserted 60 into the queue.

Inserted 70 into the queue.

Queue elements are: 30 40 50 60 70

2. Write a C program that uses functions to perform the following:

a) Create a singly linked list of integers.

Program:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for 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));

If (!newNode) {

Printf(“Memory allocation failed.\n”);

Exit(1);

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to create a singly linked list

Node* createList(Node* head, int data) {

Node* newNode = createNode(data);

If (!head) {

Return newNode; // If the list is empty, the new node becomes the head

Node* temp = head;

While (temp->next) { // Traverse to the end of the list

Temp = temp->next;

Temp->next = newNode; // Add the new node at the end

Return head;

// Function to display the contents of the list


Void displayList(Node* head) {

If (!head) {

Printf(“The list is empty.\n”);

Return;

Printf(“List contents: “);

Node* temp = head;

While (temp) {

Printf(“%d “, temp->data);

Temp = temp->next;

Printf(“\n”);

// Main function to test the program

Int main() {

Node* head = NULL;

Int choice, data;

While (1) {

Printf(“\nMenu:\n”);

Printf(“1. Add element to the list\n”);

Printf(“2. Display the list\n”);

Printf(“3. Exit\n”);

Printf(“Enter your choice: “);

Scanf(“%d”, &choice);
Switch (choice) {

Case 1:

Printf(“Enter the element to add: “);

Scanf(“%d”, &data);

Head = createList(head, data);

Break;

Case 2:

displayList(head);

break;

case 3:

printf(“Exiting the program.\n”);

exit(0);

default:

printf(“Invalid choice. Try again.\n”);

Return 0;

Output:

Menu:

1. Add element to the list

2. Display the list

3. Exit

Enter your choice: 1


Enter the element to add: 10

Menu:

1. Add element to the list

2. Display the list

3. Exit

Enter your choice: 1

Enter the element to add: 20

Menu:

1. Add element to the list

2. Display the list

3. Exit

Enter your choice: 2

List contents: 10 20

Menu:

1. Add element to the list

2. Display the list

3. Exit

Enter your choice: 3

Exiting the program.

2. Write a C program that uses functions to perform the following:


b) Delete a given integer from the above linked list.

Program :

#include <stdio.h>

#include <stdlib.h>

// Define the structure for 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));

If (!newNode) {

Printf(“Memory allocation failed.\n”);

Exit(1);

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to add a new node to the list

Node* addToList(Node* head, int data) {

Node* newNode = createNode(data);


If (!head) {

Return newNode; // If the list is empty, the new node becomes the head

Node* temp = head;

While (temp->next) { // Traverse to the end of the list

Temp = temp->next;

Temp->next = newNode; // Add the new node at the end

Return head;

// Function to delete a given integer from the list

Node* deleteNode(Node* head, int key) {

If (!head) {

Printf(“The list is empty.\n”);

Return NULL;

Node* temp = head;

Node* prev = NULL;

// If the key is in the head node

If (temp && temp->data == key) {

Head = temp->next;

Free(temp);

Printf(“Deleted %d from the list.\n”, key);

Return head;

}
// Search for the key in the list

While (temp && temp->data != key) {

Prev = temp;

Temp = temp->next;

// If the key is not found

If (!temp) {

Printf(“Element %d not found in the list.\n”, key);

Return head;

// Unlink the node and free memory

Prev->next = temp->next;

Free(temp);

Printf(“Deleted %d from the list.\n”, key);

Return head;

// Function to display the contents of the list

Void displayList(Node* head) {

If (!head) {

Printf(“The list is empty.\n”);

Return;

Printf(“List contents: “);


Node* temp = head;

While (temp) {

Printf(“%d “, temp->data);

Temp = temp->next;

Printf(“\n”);

// Main function to test the program

Int main() {

Node* head = NULL;

Int choice, data, key;

While (1) {

Printf(“\nMenu:\n”);

Printf(“1. Add element to the list\n”);

Printf(“2. Delete element from the list\n”);

Printf(“3. Display the list\n”);

Printf(“4. Exit\n”);

Printf(“Enter your choice: “);

Scanf(“%d”, &choice);

Switch (choice) {

Case 1:

Printf(“Enter the element to add: “);

Scanf(“%d”, &data);

Head = addToList(head, data);


Break;

Case 2:

Printf(“Enter the element to delete: “);

Scanf(“%d”, &key);

Head = deleteNode(head, key);

Break;

Case 3:

displayList(head);

break;

case 4:

printf(“Exiting the program.\n”);

exit(0);

default:

printf(“Invalid choice. Try again.\n”);

Return 0;

Output:

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit
Enter your choice: 1

Enter the element to add: 10

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 1

Enter the element to add: 20

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 3

List contents: 10 20

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 2

Enter the element to delete: 10

Deleted 10 from the list.


Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 3

List contents: 20

2. Write a C program that uses functions to perform the following:

C) Display the contents of the above list after deletion

Program:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for 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));


If (!newNode) {

Printf(“Memory allocation failed.\n”);

Exit(1);

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to add a new node to the list

Node* addToList(Node* head, int data) {

Node* newNode = createNode(data);

If (!head) {

Return newNode; // If the list is empty, the new node becomes the head

Node* temp = head;

While (temp->next) { // Traverse to the end of the list

Temp = temp->next;

Temp->next = newNode; // Add the new node at the end

Return head;

// Function to delete a given integer from the list

Node* deleteNode(Node* head, int key) {

If (!head) {

Printf(“The list is empty.\n”);


Return NULL;

Node* temp = head;

Node* prev = NULL;

// If the key is in the head node

If (temp && temp->data == key) {

Head = temp->next;

Free(temp);

Printf(“Deleted %d from the list.\n”, key);

Return head;

// Search for the key in the list

While (temp && temp->data != key) {

Prev = temp;

Temp = temp->next;

// If the key is not found

If (!temp) {

Printf(“Element %d not found in the list.\n”, key);

Return head;

// Unlink the node and free memory

Prev->next = temp->next;
Free(temp);

Printf(“Deleted %d from the list.\n”, key);

Return head;

// Function to display the contents of the list

Void displayList(Node* head) {

If (!head) {

Printf(“The list is empty.\n”);

Return;

Printf(“List contents: “);

Node* temp = head;

While (temp) {

Printf(“%d “, temp->data);

Temp = temp->next;

Printf(“\n”);

// Main function to test the program

Int main() {

Node* head = NULL;

Int choice, data, key;

While (1) {

Printf(“\nMenu:\n”);
Printf(“1. Add element to the list\n”);

Printf(“2. Delete element from the list\n”);

Printf(“3. Display the list\n”);

Printf(“4. Exit\n”);

Printf(“Enter your choice: “);

Scanf(“%d”, &choice);

Switch (choice) {

Case 1:

Printf(“Enter the element to add: “);

Scanf(“%d”, &data);

Head = addToList(head, data);

Break;

Case 2:

Printf(“Enter the element to delete: “);

Scanf(“%d”, &key);

Head = deleteNode(head, key);

displayList(head); // Display the list after deletion

break;

case 3:

displayList(head);

break;

case 4:

printf(“Exiting the program.\n”);

exit(0);

default:

printf(“Invalid choice. Try again.\n”);


}

Return 0;

Output:

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 1

Enter the element to add: 10

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 1

Enter the element to add: 20

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list


4. Exit

Enter your choice: 2

Enter the element to delete: 10

Deleted 10 from the list.

List contents: 20

Menu:

1. Add element to the list

2. Delete element from the list

3. Display the list

4. Exit

Enter your choice: 3

List contents: 20

3.Write a C program to implement stack ADT using linked list


implementation.

Program:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a stack 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));

If (!newNode) {

Printf(“Memory allocation failed.\n”);

Exit(1);

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to push an element onto the stack

Node* push(Node* top, int data) {

Node* newNode = createNode(data);

newNode->next = top; // Link the new node to the current top

top = newNode; // Update the top of the stack

printf(“Pushed %d onto the stack.\n”, data);

return top;

// Function to pop an element from the stack

Node* pop(Node* top, int* poppedData) {

If (!top) {

Printf(“Stack underflow! The stack is empty.\n”);

*poppedData = -1; // Indicate an error with a special value


Return NULL;

Node* temp = top;

*poppedData = temp->data;

Top = top->next; // Move the top pointer to the next node

Free(temp);

Printf(“Popped %d from the stack.\n”, *poppedData);

Return top;

// Function to peek at the top element of the stack

Int peek(Node* top) {

If (!top) {

Printf(“The stack is empty.\n”);

Return -1; // Indicate an error with a special value

Return top->data;

// Function to display the stack contents

Void displayStack(Node* top) {

If (!top) {

Printf(“The stack is empty.\n”);

Return;

Printf(“Stack contents: “);

Node* temp = top;


While (temp) {

Printf(“%d “, temp->data);

Temp = temp->next;

Printf(“\n”);

// Main function to test the stack implementation

Int main() {

Node* top = NULL; // Initialize the stack as empty

Int choice, data, poppedData;

While (1) {

Printf(“\nMenu:\n”);

Printf(“1. Push an element onto the stack\n”);

Printf(“2. Pop an element from the stack\n”);

Printf(“3. Peek at the top element\n”);

Printf(“4. Display the stack contents\n”);

Printf(“5. Exit\n”);

Printf(“Enter your choice: “);

Scanf(“%d”, &choice);

Switch (choice) {

Case 1:

Printf(“Enter the element to push: “);

Scanf(“%d”, &data);

Top = push(top, data);


Break;

Case 2:

Top = pop(top, &poppedData);

If (poppedData != -1) {

Printf(“Popped element: %d\n”, poppedData);

Break;

Case 3:

Data = peek(top);

If (data != -1) {

Printf(“Top element: %d\n”, data);

Break;

Case 4:

displayStack(top);

break;

case 5:

printf(“Exiting the program.\n”);

exit(0);

default:

printf(“Invalid choice. Try again.\n”);

Return 0;

}
Output:

Menu:

1. Push an element onto the stack

2. Pop an element from the stack

3. Peek at the top element

4. Display the stack contents

5. Exit

Enter your choice: 1

Enter the element to push: 10

Pushed 10 onto the stack.

Menu:

1. Push an element onto the stack

2. Pop an element from the stack

3. Peek at the top element

4. Display the stack contents

5. Exit

Enter your choice: 1

Enter the element to push: 20

Pushed 20 onto the stack.

Menu:

1. Push an element onto the stack

2. Pop an element from the stack

3. Peek at the top element

4. Display the stack contents

5. Exit
Enter your choice: 4

Stack contents: 20 10

Menu:

1. Push an element onto the stack

2. Pop an element from the stack

3. Peek at the top element

4. Display the stack contents

5. Exit

Enter your choice: 2

Popped 20 from the stack.

Menu:

1. Push an element onto the stack

2. Pop an element from the stack

3. Peek at the top element

4. Display the stack contents

5. Exit

Enter your choice: 4

Stack contents: 10

4. Write a c program to implement the polynomial addition and


multiplication. Use linked list implementation.
Program:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a polynomial term

Typedef struct PolyNode {

Int coefficient; // Coefficient of the term

Int exponent; // Exponent of the term

Struct PolyNode* next; // Pointer to the next term

} PolyNode;

// Function to create a new node for a term

PolyNode* createNode(int coefficient, int exponent) {

PolyNode* newNode = (PolyNode*)malloc(sizeof(PolyNode));

If (!newNode) {

Printf(“Memory allocation failed.\n”);

Exit(1);

newNode->coefficient = coefficient;

newNode->exponent = exponent;

newNode->next = NULL;

return newNode;

// Function to add a term to the polynomial

PolyNode* insertTerm(PolyNode* head, int coefficient, int exponent) {


PolyNode* newNode = createNode(coefficient, exponent);

If (!head) {

Return newNode;

PolyNode* temp = head;

While (temp->next) {

Temp = temp->next;

Temp->next = newNode;

Return head;

// Function to display a polynomial

Void displayPolynomial(PolyNode* head) {

If (!head) {

Printf(“The polynomial is empty.\n”);

Return;

PolyNode* temp = head;

While (temp) {

Printf(“%dx^%d”, temp->coefficient, temp->exponent);

If (temp->next) {

Printf(“ + “);

Temp = temp->next;

}
Printf(“\n”);

// Function to add two polynomials

PolyNode* addPolynomials(PolyNode* poly1, PolyNode* poly2) {

PolyNode* result = NULL;

While (poly1 && poly2) {

If (poly1->exponent == poly2->exponent) {

// If exponents are the same, add coefficients

Result = insertTerm(result, poly1->coefficient + poly2->coefficient,


poly1->exponent);

Poly1 = poly1->next;

Poly2 = poly2->next;

} else if (poly1->exponent > poly2->exponent) {

// If exponent of poly1 is greater, add poly1’s term

Result = insertTerm(result, poly1->coefficient, poly1->exponent);

Poly1 = poly1->next;

} else {

// If exponent of poly2 is greater, add poly2’s term

Result = insertTerm(result, poly2->coefficient, poly2->exponent);

Poly2 = poly2->next;

// Add remaining terms of poly1

While (poly1) {
Result = insertTerm(result, poly1->coefficient, poly1->exponent);

Poly1 = poly1->next;

// Add remaining terms of poly2

While (poly2) {

Result = insertTerm(result, poly2->coefficient, poly2->exponent);

Poly2 = poly2->next;

Return result;

// Function to multiply two polynomials

PolyNode* multiplyPolynomials(PolyNode* poly1, PolyNode* poly2) {

PolyNode* result = NULL;

PolyNode* temp1 = poly1;

While (temp1) {

PolyNode* temp2 = poly2;

While (temp2) {

// Multiply terms and insert the result into the result polynomial

Result = insertTerm(result, temp1->coefficient * temp2->coefficient,


temp1->exponent + temp2->exponent);

Temp2 = temp2->next;

Temp1 = temp1->next;
}

Return result;

// Main function to test polynomial addition and multiplication

Int main() {

PolyNode* poly1 = NULL;

PolyNode* poly2 = NULL;

PolyNode* sum = NULL;

PolyNode* product = NULL;

// First polynomial: 3x^3 + 5x^2 + 6x + 1

Poly1 = insertTerm(poly1, 3, 3);

Poly1 = insertTerm(poly1, 5, 2);

Poly1 = insertTerm(poly1, 6, 1);

Poly1 = insertTerm(poly1, 1, 0);

// Second polynomial: 4x^3 + 2x^2 + 7

Poly2 = insertTerm(poly2, 4, 3);

Poly2 = insertTerm(poly2, 2, 2);

Poly2 = insertTerm(poly2, 7, 0);

// Displaying both polynomials

Printf(“First Polynomial: “);

displayPolynomial(poly1);
printf(“Second Polynomial: “);

displayPolynomial(poly2);

// Adding the polynomials

Sum = addPolynomials(poly1, poly2);

Printf(“\nSum of the polynomials: “);

displayPolynomial(sum);

// Multiplying the polynomials

Product = multiplyPolynomials(poly1, poly2);

Printf(“\nProduct of the polynomials: “);

displayPolynomial(product);

return 0;

Output:

First Polynomial: 3x^3 + 5x^2 + 6x + 1

Second Polynomial: 4x^3 + 2x^2 + 7

Sum of the polynomials: 7x^3 + 7x^2 + 6x + 8

Product of the polynomials: 12x^6 + 26x^5 + 50x^4 + 43x^3 + 12x^2 + 7


5. infix to postfix conversion

Program:

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

// Define the maximum size of the stack

#define MAX 100

// Stack structure

Typedef struct Stack {

Int top;

Char items[MAX];

} Stack;

// Function to initialize the stack

Void initStack(Stack* s) {

s->top = -1;

// Function to check if the stack is empty

Int isEmpty(Stack* s) {

Return s->top == -1;


}

// Function to check if the stack is full

Int isFull(Stack* s) {

Return s->top == MAX – 1;

// Function to push an element onto the stack

Void push(Stack* s, char item) {

If (isFull(s)) {

Printf(“Stack overflow!\n”);

Return;

s->items[++(s->top)] = item;

// Function to pop an element from the stack

Char pop(Stack* s) {

If (isEmpty(s)) {

Printf(“Stack underflow!\n”);

Return -1;

Return s->items[(s->top)--];

// Function to peek at the top element of the stack

Char peek(Stack* s) {
If (!isEmpty(s)) {

Return s->items[s->top];

Return -1;

// Function to check precedence of operators

Int precedence(char op) {

If (op == ‘^’) return 3;

If (op == ‘*’ || op == ‘/’) return 2;

If (op == ‘+’ || op == ‘-‘) return 1;

Return 0;

// Function to check if a character is an operator

Int isOperator(char c) {

Return (c == ‘+’ || c == ‘-‘ || c == ‘*’ || c == ‘/’ || c == ‘^’);

// Function to convert infix to postfix

Void infixToPostfix(char* infix, char* postfix) {

Stack s;

initStack(&s);

int I = 0, j = 0;

while (infix[i] != ‘\0’) {

char current = infix[i];


if (isalnum(current)) {

// If the character is an operand, add it to the result

Postfix[j++] = current;

} else if (current == ‘(‘) {

// If the character is ‘(‘, push it to the stack

Push(&s, current);

} else if (current == ‘)’) {

// If the character is ‘)’, pop from the stack until ‘(‘ is found

While (!isEmpty(&s) && peek(&s) != ‘(‘) {

Postfix[j++] = pop(&s);

Pop(&s); // Remove ‘(‘ from the stack

} else if (isOperator(current)) {

// If the character is an operator

While (!isEmpty(&s) && precedence(peek(&s)) >=


precedence(current)) {

Postfix[j++] = pop(&s);

Push(&s, current);

I++;

// Pop all the remaining operators from the stack

While (!isEmpty(&s)) {

Postfix[j++] = pop(&s);
}

Postfix[j] = ‘\0’; // Null-terminate the postfix expression

Int main() {

Char infix[MAX], postfix[MAX];

Printf(“Enter an infix expression: “);

Scanf(“%s”, infix);

infixToPostfix(infix, postfix);

printf(“Postfix expression: %s\n”, postfix);

return 0;

Output:

Enter an infix expression: A+B*(C^D-E)^(F+G*H)-I

Postfix expression: ABCD^E-FGH*+^*+I-

6. binary search tree


Program:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a node in the binary search tree

Typedef struct Node {

Int data;

Struct Node* left;

Struct Node* right;

} Node;

// Function to create a new node with a given value

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

If (!newNode) {

Printf(“Memory allocation failed!\n”);

Exit(1);

newNode->data = data;

newNode->left = newNode->right = NULL;

return newNode;

// Function to insert a node in the BST

Node* insertNode(Node* root, int data) {

// If the tree is empty, create a new node

If (root == NULL) {
Return createNode(data);

// Otherwise, recur down the tree

If (data < root->data) {

Root->left = insertNode(root->left, data); // Insert in left subtree

} else if (data > root->data) {

Root->right = insertNode(root->right, data); // Insert in right subtree

// Return the (unchanged) node pointer

Return root;

// Function to search for a node in the BST

Node* search(Node* root, int data) {

// Base case: root is null or data is present at the root

If (root == NULL || root->data == data) {

Return root;

// If data is smaller, search in the left subtree

If (data < root->data) {

Return search(root->left, data);

// If data is larger, search in the right subtree


Return search(root->right, data);

// In-order traversal of the BST (Left, Root, Right)

Void inorderTraversal(Node* root) {

If (root != NULL) {

inorderTraversal(root->left); // Visit left subtree

printf(“%d “, root->data); // Visit root

inorderTraversal(root->right); // Visit right subtree

// Main function to demonstrate BST functionality

Int main() {

Node* root = NULL;

// Inserting nodes into the BST

Root = insertNode(root, 50);

Root = insertNode(root, 30);

Root = insertNode(root, 20);

Root = insertNode(root, 40);

Root = insertNode(root, 70);

Root = insertNode(root, 60);

Root = insertNode(root, 80);

// Performing in-order traversal (should print sorted order)

Printf(“In-order traversal of the BST: “);


inorderTraversal(root);

printf(“\n”);

// Searching for a value in the BST

Int searchValue = 40;

Node* foundNode = search(root, searchValue);

If (foundNode != NULL) {

Printf(“Node with value %d found in the BST.\n”, searchValue);

} else {

Printf(“Node with value %d not found in the BST.\n”, searchValue);

Return 0;

Output:

In-order traversal of the BST: 20 30 40 50 60 70 80

Node with value 40 found in the BST.

50

/ \

30 70

/ \ / \

20 40 60 80
7. AVL trees and its operations

Program:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a node in the AVL tree

Typedef struct Node {

Int data;

Struct Node* left;

Struct Node* right;

Int height;

} Node;

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

If (!newNode) {

Printf(“Memory allocation failed!\n”);

Exit(1);

newNode->data = data;

newNode->left = newNode->right = NULL;

newNode->height = 1; // New node is initially at height 1

return newNode;

}
// Function to get the height of a node

Int height(Node* root) {

Return root == NULL ? 0 : root->height;

// Function to get the balance factor of a node

Int getBalance(Node* root) {

Return root == NULL ? 0 : height(root->left) – height(root->right);

// Right rotate utility

Node* rightRotate(Node* y) {

Node* x = y->left;

Node* T2 = x->right;

// Perform rotation

x->right = y;

y->left = T2;

// Update heights

y->height = 1 + (height(y->left) > height(y->right) ? height(y->left) :


height(y->right));

x->height = 1 + (height(x->left) > height(x->right) ? height(x->left) :


height(x->right));

// Return the new root

Return x;
}

// Left rotate utility

Node* leftRotate(Node* x) {

Node* y = x->right;

Node* T2 = y->left;

// Perform rotation

y->left = x;

x->right = T2;

// Update heights

x->height = 1 + (height(x->left) > height(x->right) ? height(x->left) :


height(x->right));

y->height = 1 + (height(y->left) > height(y->right) ? height(y->left) :


height(y->right));

// Return the new root

Return y;

// Function to insert a node in the AVL tree

Node* insert(Node* root, int data) {

// 1. Perform the normal BST insertion

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);

} else {

Return root; // Duplicate values are not allowed

// 2. Update the height of this ancestor node

Root->height = 1 + (height(root->left) > height(root->right) ? height(root-


>left) : height(root->right));

// 3. Get the balance factor of this ancestor node

Int balance = getBalance(root);

// 4. If the node becomes unbalanced, then there are 4 cases

// Left-Left (LL) Case

If (balance > 1 && data < root->left->data) {

Return rightRotate(root);

// Right-Right (RR) Case

If (balance < -1 && data > root->right->data) {

Return leftRotate(root);

}
// Left-Right (LR) Case

If (balance > 1 && data > root->left->data) {

Root->left = leftRotate(root->left);

Return rightRotate(root);

// Right-Left (RL) Case

If (balance < -1 && data < root->right->data) {

Root->right = rightRotate(root->right);

Return leftRotate(root);

// Return the (unchanged) node pointer

Return root;

// Function to perform in-order traversal of the AVL tree

Void inorderTraversal(Node* root) {

If (root != NULL) {

inorderTraversal(root->left);

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

inorderTraversal(root->right);

// Main function to demonstrate AVL tree functionality


Int main() {

Node* root = NULL;

// Insert elements into the AVL tree

Root = insert(root, 10);

Root = insert(root, 20);

Root = insert(root, 30);

Root = insert(root, 15);

Root = insert(root, 25);

Root = insert(root, 5);

// Perform in-order traversal (should print sorted order)

Printf(“In-order traversal of the AVL tree: “);

inorderTraversal(root);

printf(“\n”);

return 0;

Output:

In-order traversal of the AVL tree: 5 10 15 20 25 30

8. binary heap using priority queues


Program:

#include <stdio.h>

#include <stdlib.h>

// Function to swap two elements

Void swap(int* a, int* b) {

Int temp = *a;

*a = *b;

*b = temp;

// Function to heapify a subtree rooted with node i

// n is the size of the heap

Void heapify(int arr[], int n, int i) {

Int largest = I; // Initialize largest as root

Int left = 2 * I + 1; // left child

Int right = 2 * I + 2; // right child

// If left child is larger than root

If (left < n && arr[left] > arr[largest]) {

Largest = left;

// If right child is larger than largest so far

If (right < n && arr[right] > arr[largest]) {


Largest = right;

// If largest is not root, swap and continue heapifying

If (largest != i) {

Swap(&arr[i], &arr[largest]);

Heapify(arr, n, largest);

// Function to insert a new element into the heap

Void insert(int arr[], int* n, int key) {

// Increase size of heap and add the new element at the end

(*n)++;

Int I = *n – 1;

Arr[i] = key;

// Fix the heap property if it’s violated

While (I != 0 && arr[(I – 1) / 2] < arr[i]) {

Swap(&arr[i], &arr[(I – 1) / 2]);

I = (I – 1) / 2;

// Function to delete the root (extract maximum) from the heap

Int extractMax(int arr[], int* n) {

If (*n <= 0) {
Printf(“Heap is empty!\n”);

Return -1;

// Store the maximum value (root)

Int root = arr[0];

// Replace the root with the last element

Arr[0] = arr[*n – 1];

(*n)--;

// Heapify the root to restore heap property

Heapify(arr, *n, 0);

Return root;

// Function to display the heap array

Void display(int arr[], int n) {

For (int I = 0; I < n; i++) {

Printf(“%d “, arr[i]);

Printf(“\n”);

// Main function to demonstrate Binary Heap operations

Int main() {
Int heap[100]; // Array to represent the heap

Int n = 0; // Size of the heap

// Insert elements into the heap

Insert(heap, &n, 10);

Insert(heap, &n, 20);

Insert(heap, &n, 15);

Insert(heap, &n, 30);

Insert(heap, &n, 5);

// Display the heap

Printf(“Heap after insertions: “);

Display(heap, n);

// Extract the maximum element (root) from the heap

Int max = extractMax(heap, &n);

Printf(“Extracted maximum element: %d\n”, max);

// Display the heap after extraction

Printf(“Heap after extraction: “);

Display(heap, n);

Return 0;

Output:
Heap after insertions: 30 20 15 10 5

Extracted maximum element: 30

Heap after extraction: 20 10 15 5

9. Dijkstra’s algorithm

Program:

#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

// Number of vertices in the graph

#define V 9

// Function to find the vertex with the minimum distance that hasn’t been
visited

Int minDistance(int dist[], int visited[]) {

Int min = INT_MAX, min_index;

For (int v = 0; v < V; v++) {

If (visited[v] == 0 && dist[v] <= min) {

Min = dist[v];

Min_index = v;
}

Return min_index;

// Function to implement Dijkstra’s algorithm

Void dijkstra(int graph[V][V], int start) {

Int dist[V]; // dist[i] will hold the shortest distance from start to i

Int visited[V]; // visited[i] will be 1 if vertex I is included in the shortest


path

Int parent[V]; // Array to store the path

// Initialize all distances as INFINITE and visited[] as false

For (int I = 0; I < V; i++) {

Dist[i] = INT_MAX;

Visited[i] = 0;

Parent[i] = -1;

// Distance from the start vertex to itself is always 0

Dist[start] = 0;

// Find the shortest path for all vertices

For (int count = 0; count < V – 1; count++) {

// Get the vertex with the minimum distance

Int u = minDistance(dist, visited);


// Mark the selected vertex as visited

Visited[u] = 1;

// Update dist value of the adjacent vertices of the selected vertex

For (int v = 0; v < V; v++) {

// Update dist[v] if the current path is shorter and v is not visited

If (!visited[v] && graph[u][v] != 0 && dist[u] != INT_MAX && dist[u] +


graph[u][v] < dist[v]) {

Dist[v] = dist[u] + graph[u][v];

Parent[v] = u;

// Print the shortest distances and the paths

Printf(“Vertex\tDistance from Source\tPath\n”);

For (int I = 0; I < V; i++) {

Printf(“%d\t\t%d\t\t\t”, I, dist[i]);

// Print the path

Int j = I;

While (parent[j] != -1) {

Printf(“%d <- “, j);

J = parent[j];

Printf(“%d\n”, start);
}

Int main() {

// Example graph represented as an adjacency matrix

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, 14, 10, 0, 2, 0, 0},

{0, 0, 0, 0, 0, 2, 0, 1, 6},

{8, 11, 0, 0, 0, 0, 1, 0, 7},

{0, 0, 2, 0, 0, 0, 6, 7, 0}

};

// Call Dijkstra’s algorithm with source vertex 0

Dijkstra(graph, 0);

Return 0;

Output:

Vertex Distance from Source Path

0 0 0
1 4 1 <- 0

2 12 2 <- 5 <- 0

3 19 3 <- 2 <- 5 <- 0

4 21 4 <- 5 <- 0

5 11 5 <- 0

6 9 6 <- 7 <- 2 <- 5 <- 0

7 8 7 <- 0

8 14 8 <- 2 <- 5 <- 0

10. Prim’s algorithm

Program:

#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

// Number of vertices in the graph

#define V 9

// Function to find the vertex with the minimum key value that hasn’t been
included in MST

Int minKey(int key[], int mstSet[]) {


Int min = INT_MAX, min_index;

For (int v = 0; v < V; v++) {

If (mstSet[v] == 0 && key[v] < min) {

Min = key[v];

Min_index = v;

Return min_index;

// Function to implement Prim’s Algorithm to find the MST

Void primMST(int graph[V][V]) {

Int parent[V]; // Array to store the MST

Int key[V]; // Key values to pick the minimum weight edge

Int mstSet[V]; // To represent the set of vertices included in MST

// Initialize all keys as infinity and mstSet[] as false

For (int I = 0; I < V; i++) {

Key[i] = INT_MAX;

mstSet[i] = 0;

// Start with the first vertex (arbitrary choice)

Key[0] = 0; // Make the first vertex the root of the MST

Parent[0] = -1; // First node is always root

// The MST will have V vertices


For (int count = 0; count < V – 1; count++) {

// Pick the vertex with the minimum key value that is not yet included in
MST

Int u = minKey(key, mstSet);

// Add the picked vertex to the MST set

mstSet[u] = 1;

// Update the key and parent values of the adjacent vertices of the
picked vertex

For (int v = 0; v < V; v++) {

// Update the key only if the edge (u, v) is smaller than the current
key[v]

// and v is not yet included in MST

If (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {

Key[v] = graph[u][v];

Parent[v] = u;

// Print the MST

Printf(“Edge\tWeight\n”);

For (int I = 1; I < V; i++) {

Printf(“%d - %d\t%d\n”, parent[i], I, graph[i][parent[i]]);

}
Int main() {

// Example graph represented as an adjacency matrix

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, 14, 10, 0, 2, 0, 0},

{0, 0, 0, 0, 0, 2, 0, 1, 6},

{8, 11, 0, 0, 0, 0, 1, 0, 7},

{0, 0, 2, 0, 0, 0, 6, 7, 0}

};

// Call Prim’s algorithm to find the MST of the graph

primMST(graph);

return 0;

Output:

Edge Weight

0–1 4

1–2 8

2–5 4

5–6 2
6–7 1

7–8 7

2–3 7

3–4 9

11. linear search

Program:

#include <stdio.h>

// Function to implement linear search

Int linearSearch(int arr[], int size, int target) {

// Traverse the array to find the target

For (int I = 0; I < size; i++) {

If (arr[i] == target) {

Return I; // Return the index if target is found

Return -1; // Return -1 if target is not found

Int main() {

Int arr[] = {2, 5, 7, 9, 3, 4, 1, 8, 6}; // Example array


Int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

Int target, result;

// Input the target value to search for

Printf(“Enter the number to search: “);

Scanf(“%d”, &target);

// Perform linear search

Result = linearSearch(arr, size, target);

// Display the result

If (result != -1) {

Printf(“Element found at index: %d\n”, result);

} else {

Printf(“Element not found in the array.\n”);

Return 0;

Output:

Enter the number to search: 3

Element found at index: 4


12. insertion sort

Program:

#include <stdio.h>

// Function to implement Insertion Sort

Void insertionSort(int arr[], int n) {

Int key, j;

// Traverse through 1 to n-1 elements

For (int I = 1; I < n; i++) {

Key = arr[i]; // Store the current element to be inserted

J = I – 1;

// Move elements of arr[0..i-1] that are greater than key, to one position
ahead

While (j >= 0 && arr[j] > key) {

Arr[j + 1] = arr[j]; // Shift element to the right

J = j – 1;

Arr[j + 1] = key; // Insert the key in the correct position

}
// Function to print the array

Void printArray(int arr[], int n) {

For (int I = 0; I < n; i++) {

Printf(“%d “, arr[i]);

Printf(“\n”);

Int main() {

Int arr[] = {12, 11, 13, 5, 6}; // Example array

Int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

Printf(“Original array: “);

printArray(arr, n);

// Perform Insertion Sort

insertionSort(arr, n);

printf(“Sorted array: “);

printArray(arr, n);

return 0;

Output:

Original array: 12 11 13 5 6

Sorted array: 5 6 11 12 13
13. merge sort

Program:

#include <stdio.h>

// Function to merge two halves of an array

Void merge(int arr[], int left, int mid, int right) {

Int n1 = mid – left + 1; // Size of the left subarray

Int n2 = right – mid; // Size of the right subarray

// Temporary arrays for left and right subarrays

Int leftArr[n1], rightArr[n2];

// Copy data to temporary arrays

For (int I = 0; I < n1; i++)

leftArr[i] = arr[left + i];

for (int j = 0; j < n2; j++)

rightArr[j] = arr[mid + 1 + j];

int I = 0, j = 0, k = left;

// Merge the temporary arrays back into the original array


While (I < n1 && j < n2) {

If (leftArr[i] <= rightArr[j]) {

Arr[k] = leftArr[i];

I++;

} else {

Arr[k] = rightArr[j];

J++;

K++;

// Copy remaining elements of leftArr[], if any

While (I < n1) {

Arr[k] = leftArr[i];

I++;

K++;

// Copy remaining elements of rightArr[], if any

While (j < n2) {

Arr[k] = rightArr[j];

J++;

K++;

// Function to implement Merge Sort


Void mergeSort(int arr[], int left, int right) {

If (left < right) {

// Find the middle point

Int mid = left + (right – left) / 2;

// Recursively sort the two halves

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

// Merge the sorted halves

Merge(arr, left, mid, right);

// Function to print the array

Void printArray(int arr[], int size) {

For (int I = 0; I < size; i++) {

Printf(“%d “, arr[i]);

Printf(“\n”);

Int main() {

Int arr[] = {12, 11, 13, 5, 6, 7}; // Example array

Int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

Printf(“Original array: “);


printArray(arr, size);

// Perform Merge Sort

mergeSort(arr, 0, size – 1);

printf(“Sorted array: “);

printArray(arr, size);

return 0;

Output:

Original array: 12 11 13 5 6 7

Sorted array: 5 6 7 11 12 13

14. max heap tree

Program:

#include <stdio.h>

#define MAX 100 // Maximum number of elements in the heap


// Max heap array

Int heap[MAX];

Int heapSize = 0; // Current size of the heap

// Function to swap two elements in the heap

Void swap(int *a, int *b) {

Int temp = *a;

*a = *b;

*b = temp;

// Function to heapify a subtree rooted at index i

Void heapify(int i) {

Int left = 2 * I + 1; // Left child index

Int right = 2 * I + 2; // Right child index

Int largest = I;

// If the left child is larger than root

If (left < heapSize && heap[left] > heap[largest]) {

Largest = left;

// If the right child is larger than the largest so far

If (right < heapSize && heap[right] > heap[largest]) {

Largest = right;

}
// If the largest is not root, swap and continue heapifying

If (largest != i) {

Swap(&heap[i], &heap[largest]);

Heapify(largest);

// Function to insert a new element into the max heap

Void insert(int value) {

If (heapSize == MAX) {

Printf(“Heap is full\n”);

Return;

// Insert the new element at the end of the heap

Heap[heapSize] = value;

Int I = heapSize;

heapSize++;

// Fix the max heap property if it is violated

While (I != 0 && heap[(I – 1) / 2] < heap[i]) {

Swap(&heap[i], &heap[(I – 1) / 2]);

I = (I – 1) / 2; // Move up the tree

// Function to extract the maximum element (root) from the max heap
Int extractMax() {

If (heapSize <= 0) {

Printf(“Heap is empty\n”);

Return -1;

If (heapSize == 1) {

heapSize--;

return heap[0];

// Store the root value (maximum)

Int root = heap[0];

// Replace the root with the last element in the heap

Heap[0] = heap[heapSize – 1];

heapSize--;

// Heapify the root to restore the heap property

Heapify(0);

Return root;

// Function to print the heap

Void printHeap() {

For (int I = 0; I < heapSize; i++) {

Printf(“%d “, heap[i]);
}

Printf(“\n”);

Int main() {

Insert(10);

Insert(20);

Insert(30);

Insert(5);

Insert(15);

Printf(“Max Heap: “);

printHeap();

printf(“Extracted max: %d\n”, extractMax());

printf(“Heap after extraction: “);

printHeap();

return 0;

Output:

Max Heap: 30 20 10 5 15

Extracted max: 30

Heap after extraction: 20 15 10 5


15. List ADT – polynomial subtraction

Program:

#include <stdio.h>

#include <stdlib.h>

// Structure to represent a node of a polynomial

Struct Node {

Int coeff; // Coefficient of the term

Int exp; // Exponent of the term

Struct Node* next; // Pointer to the next node

};

// Function to create a new node with the given coefficient and exponent

Struct Node* createNode(int coeff, int exp) {

Struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->coeff = coeff;

newNode->exp = exp;

newNode->next = NULL;

return newNode;

}
// Function to insert a term in the polynomial (in descending order of
exponent)

Void insertTerm(struct Node** poly, int coeff, int exp) {

Struct Node* newNode = createNode(coeff, exp);

// If the polynomial is empty or the new node has higher exponent

If (*poly == NULL || (*poly)->exp < exp) {

newNode->next = *poly;

*poly = newNode;

} else {

Struct Node* temp = *poly;

While (temp->next != NULL && temp->next->exp > exp) {

Temp = temp->next;

If (temp->next != NULL && temp->next->exp == exp) {

Temp->next->coeff += coeff;

} else {

newNode->next = temp->next;

temp->next = newNode;

// Function to print a polynomial

Void printPolynomial(struct Node* poly) {

If (poly == NULL) {
Printf(“Polynomial is empty.\n”);

Return;

While (poly != NULL) {

If (poly->coeff > 0 && poly != poly->next) {

Printf(“+”);

Printf(“%dx^%d “, poly->coeff, poly->exp);

Poly = poly->next;

Printf(“\n”);

// Function to subtract two polynomials

Struct Node* subtractPolynomials(struct Node* poly1, struct Node* poly2) {

Struct Node* result = NULL;

While (poly1 != NULL && poly2 != NULL) {

If (poly1->exp > poly2->exp) {

insertTerm(&result, poly1->coeff, poly1->exp);

poly1 = poly1->next;

} else if (poly1->exp < poly2->exp) {

insertTerm(&result, -poly2->coeff, poly2->exp); // Subtract term of


poly2

poly2 = poly2->next;

} else {

Int diff = poly1->coeff – poly2->coeff;


If (diff != 0) {

insertTerm(&result, diff, poly1->exp);

Poly1 = poly1->next;

Poly2 = poly2->next;

// If poly1 still has terms left, add them

While (poly1 != NULL) {

insertTerm(&result, poly1->coeff, poly1->exp);

poly1 = poly1->next;

// If poly2 still has terms left, subtract them

While (poly2 != NULL) {

insertTerm(&result, -poly2->coeff, poly2->exp);

poly2 = poly2->next;

Return result;

// Main function to demonstrate polynomial subtraction

Int main() {

Struct Node* poly1 = NULL;

Struct Node* poly2 = NULL;


Struct Node* result = NULL;

// Polynomial 1: 3x^3 + 2x^2 – x + 5

insertTerm(&poly1, 3, 3);

insertTerm(&poly1, 2, 2);

insertTerm(&poly1, -1, 1);

insertTerm(&poly1, 5, 0);

// Polynomial 2: 5x^3 – 2x^2 + 4x – 3

insertTerm(&poly2, 5, 3);

insertTerm(&poly2, -2, 2);

insertTerm(&poly2, 4, 1);

insertTerm(&poly2, -3, 0);

printf(“Polynomial 1: “);

printPolynomial(poly1);

printf(“Polynomial 2: “);

printPolynomial(poly2);

// Perform polynomial subtraction: poly1 – poly2

Result = subtractPolynomials(poly1, poly2);

Printf(“Result of Polynomial Subtraction: “);

printPolynomial(result);

return 0;
}

Output:

Polynomial 1: +3x^3 +2x^2 -1x^1 +5x^0

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

Result of Polynomial Subtraction: -2x^3 +4x^2 -5x^1 +8x^0

16. evaluate postfix expression

Program:

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

// Define a stack structure

#define MAX 50

Int stack[MAX];

Int top = -1;

// Function to push an element onto the stack

Void push(int value) {

If (top < MAX – 1) {


Stack[++top] = value;

} else {

Printf(“Stack Overflow\n”);

// Function to pop an element from the stack

Int pop() {

If (top >= 0) {

Return stack[top--];

} else {

Printf(“Stack Underflow\n”);

Return -1;

// Function to evaluate a postfix expression

Int evaluatePostfix(char* expression) {

Int I = 0;

While (expression[i] != ‘\0’) {

// If the character is an operand (digit), push it onto the stack

If (isdigit(expression[i])) {

Push(expression[i] – ‘0’); // Convert char to integer

// If the character is an operator, pop two operands and apply the


operator

Else {
Int operand2 = pop();

Int operand1 = pop();

Switch (expression[i]) {

Case ‘+’:

Push(operand1 + operand2);

Break;

Case ‘-‘:

Push(operand1 – operand2);

Break;

Case ‘*’:

Push(operand1 * operand2);

Break;

Case ‘/’:

Push(operand1 / operand2);

Break;

Default:

Printf(“Invalid operator encountered: %c\n”, expression[i]);

Return -1;

I++;

Return pop(); // The result is the last element in the stack

Int main() {
Char expression[MAX];

Printf(“Enter a postfix expression: “);

Fgets(expression, MAX, stdin); // Read the postfix expression

// Evaluate the postfix expression

Int result = evaluatePostfix(expression);

// Output the result

If (result != -1) {

Printf(“Result of the postfix expression: %d\n”, result);

Return 0;

Output:

Enter a postfix expression: 23+5*

Result of the postfix expression: 25

Enter a postfix expression: 34+2*

Result of the postfix expression: 14


17. queue ADT

Program:

#include <stdio.h>

#include <stdlib.h>

#define MAX 5 // Maximum size of the queue

// Queue structure

Struct Queue {

Int items[MAX];

Int front;

Int rear;

};

// Function to initialize the queue

Void initializeQueue(struct Queue* q) {

q->front = -1;

q->rear = -1;

// Function to check if the queue is full

Int isFull(struct Queue* q) {

If ((q->rear + 1) % MAX == q->front) {

Return 1;
}

Return 0;

// Function to check if the queue is empty

Int isEmpty(struct Queue* q) {

If (q->front == -1) {

Return 1;

Return 0;

// Function to enqueue an element

Void enqueue(struct Queue* q, int value) {

If (isFull(q)) {

Printf(“Queue is full. Cannot enqueue %d\n”, value);

Return;

If (q->front == -1) {

q->front = 0; // First element enqueued

q->rear = (q->rear + 1) % MAX;

q->items[q->rear] = value;

printf(“%d enqueued to the queue\n”, value);

}
// Function to dequeue an element

Int dequeue(struct Queue* q) {

If (isEmpty(q)) {

Printf(“Queue is empty. Cannot dequeue\n”);

Return -1;

Int item = q->items[q->front];

If (q->front == q->rear) {

q->front = q->rear = -1; // Queue is now empty

} else {

q->front = (q->front + 1) % MAX;

Return item;

// Function to view the element at the front of the queue

Int front(struct Queue* q) {

If (isEmpty(q)) {

Printf(“Queue is empty\n”);

Return -1;

Return q->items[q->front];

}
// Function to display the elements in the queue

Void display(struct Queue* q) {

If (isEmpty(q)) {

Printf(“Queue is empty\n”);

Return;

Printf(“Queue contents: “);

Int I = q->front;

While (I != q->rear) {

Printf(“%d “, q->items[i]);

I = (I + 1) % MAX;

Printf(“%d\n”, q->items[q->rear]);

// Main function to test the queue implementation

Int main() {

Struct Queue q;

initializeQueue(&q);

// Testing the queue operations

Enqueue(&q, 10);

Enqueue(&q, 20);

Enqueue(&q, 30);
Enqueue(&q, 40);

Enqueue(&q, 50); // Queue is full now

Display(&q);

Printf(“Dequeued: %d\n”, dequeue(&q)); // Dequeue an element

Display(&q);

Enqueue(&q, 60); // Enqueue another element

Display(&q);

Printf(“Front element: %d\n”, front(&q));

Return 0;

Output:

10 enqueued to the queue

20 enqueued to the queue

30 enqueued to the queue

40 enqueued to the queue

50 enqueued to the queue

Queue contents: 10 20 30 40 50

Dequeued: 10

Queue contents: 20 30 40 50
60 enqueued to the queue

Queue contents: 20 30 40 50 60

Front element: 20

18. singly link list

Program:

#include <stdio.h>

#include <stdlib.h>

// Definition of a node in the singly linked list

Struct Node {

Int data; // Data of the node

Struct Node* next; // Pointer to the next node

};

// Function to create a new node

Struct Node* createNode(int data) {

Struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->data = data;

newNode->next = NULL;

return newNode;
}

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

Void insertAtBeginning(struct Node** head, int data) {

Struct Node* newNode = createNode(data);

newNode->next = *head; // New node points to the current head

*head = newNode; // Head now points to the new node

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

Void insertAtEnd(struct Node** head, int data) {

Struct Node* newNode = createNode(data);

If (*head == NULL) {

*head = newNode; // If the list is empty, make the new node the head

Return;

Struct Node* temp = *head;

While (temp->next != NULL) {

Temp = temp->next; // Traverse to the last node

Temp->next = newNode; // Last node’s next points to the new node

// Function to delete a node from the list

Void deleteNode(struct Node** head, int key) {

Struct Node* temp = *head;

Struct Node* prev = NULL;


// If the node to be deleted is the head

If (temp != NULL && temp->data == key) {

*head = temp->next; // Move the head to the next node

Free(temp); // Free the memory of the node

Return;

// Search for the node to be deleted

While (temp != NULL && temp->data != key) {

Prev = temp;

Temp = temp->next;

// If the key was not found

If (temp == NULL) {

Printf(“Node with value %d not found.\n”, key);

Return;

Prev->next = temp->next; // Unlink the node from the list

Free(temp); // Free the memory of the node

// Function to display the list

Void displayList(struct Node* head) {

Struct Node* temp = head;


If (temp == NULL) {

Printf(“The list is empty.\n”);

Return;

While (temp != NULL) {

Printf(“%d -> “, temp->data);

Temp = temp->next;

Printf(“NULL\n”);

// Main function to test the singly linked list operations

Int main() {

Struct Node* head = NULL;

// Insert elements at the beginning and end

insertAtBeginning(&head, 10);

insertAtBeginning(&head, 20);

insertAtEnd(&head, 30);

insertAtEnd(&head, 40);

// Display the linked list

Printf(“Linked List: “);

displayList(head);

// Delete a node

deleteNode(&head, 20); // Delete node with data 20


printf(“After deleting node with value 20: “);

displayList(head);

deleteNode(&head, 50); // Attempt to delete a node not present in the list

return 0;

Output:

Linked List: 20 -> 10 -> 30 -> 40 -> NULL

After deleting node with value 20: 10 -> 30 -> 40 -> NULL

Node with value 50 not found.

19. stack using linked list

Program:

#include <stdio.h>

#include <stdlib.h>

// Definition of a node in the stack


Struct Node {

Int data; // Data of the node

Struct Node* next; // Pointer to the next node

};

// Function to create a new node

Struct Node* createNode(int data) {

Struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to push an element onto the stack

Void push(struct Node** top, int data) {

Struct Node* newNode = createNode(data);

newNode->next = *top; // New node points to the current top

*top = newNode; // Top now points to the new node

Printf(“%d pushed onto the stack\n”, data);

// Function to pop an element from the stack

Int pop(struct Node** top) {

If (*top == NULL) {

Printf(“Stack underflow! Stack is empty.\n”);

Return -1; // Indicates the stack is empty

}
Struct Node* temp = *top;

Int poppedData = temp->data; // Store the data to be popped

*top = (*top)->next; // Move top to the next node

Free(temp); // Free the memory of the popped node

Return poppedData;

// Function to peek at the top element of the stack

Int peek(struct Node* top) {

If (top == NULL) {

Printf(“Stack is empty.\n”);

Return -1;

Return top->data; // Return the top element without removing it

// Function to check if the stack is empty

Int isEmpty(struct Node* top) {

Return top == NULL;

// Function to display all elements in the stack

Void display(struct Node* top) {

If (top == NULL) {

Printf(“Stack is empty.\n”);

Return;
}

Printf(“Stack elements: “);

Struct Node* temp = top;

While (temp != NULL) {

Printf(“%d “, temp->data);

Temp = temp->next;

Printf(“\n”);

// Main function to test the stack implementation

Int main() {

Struct Node* stack = NULL; // Initialize the stack (empty stack)

// Test the stack operations

Push(&stack, 10);

Push(&stack, 20);

Push(&stack, 30);

Push(&stack, 40);

Display(stack); // Display the stack

Printf(“Peek: %d\n”, peek(stack)); // Peek at the top element

Printf(“Popped: %d\n”, pop(&stack)); // Pop an element

Display(stack); // Display the stack after pop


Printf(“Popped: %d\n”, pop(&stack)); // Pop another element

Display(stack); // Display the stack after another pop

Push(&stack, 50); // Push a new element onto the stack

Display(stack); // Display the stack after pushing 50

Return 0;

Output:

10 pushed onto the stack

20 pushed onto the stack

30 pushed onto the stack

40 pushed onto the stack

Stack elements: 40 30 20 10

Peek: 40

Popped: 40

Stack elements: 30 20 10

Popped: 30

Stack elements: 20 10

50 pushed onto the stack

Stack elements: 50 20 10
20. implementation of polynomial manipulation

Program:

#include <stdio.h>

#include <stdlib.h>

// Definition of a node in the polynomial linked list

Struct Node {

Int coefficient; // Coefficient of the term

Int exponent; // Exponent of the term

Struct Node* next; // Pointer to the next term

};

// Function to create a new node

Struct Node* createNode(int coeff, int exp) {

Struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->coefficient = coeff;

newNode->exponent = exp;

newNode->next = NULL;

return newNode;

}
// Function to insert a term in the polynomial in descending order of
exponents

Void insertTerm(struct Node** poly, int coeff, int exp) {

Struct Node* newNode = createNode(coeff, exp);

If (*poly == NULL || (*poly)->exponent < exp) {

newNode->next = *poly;

*poly = newNode;

Return;

Struct Node* temp = *poly;

While (temp->next != NULL && temp->next->exponent > exp) {

Temp = temp->next;

If (temp->next != NULL && temp->next->exponent == exp) {

Temp->next->coefficient += coeff;

Free(newNode);

} else {

newNode->next = temp->next;

temp->next = newNode;

// Function to display the polynomial

Void displayPolynomial(struct Node* poly) {


If (poly == NULL) {

Printf(“0\n”);

Return;

Struct Node* temp = poly;

While (temp != NULL) {

Printf(“%dx^%d”, temp->coefficient, temp->exponent);

If (temp->next != NULL && temp->next->coefficient > 0) {

Printf(“ + “);

Temp = temp->next;

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;

While (temp1 != NULL && temp2 != NULL) {

If (temp1->exponent > temp2->exponent) {

insertTerm(&result, temp1->coefficient, temp1->exponent);

temp1 = temp1->next;

} else if (temp1->exponent < temp2->exponent) {


insertTerm(&result, temp2->coefficient, temp2->exponent);

temp2 = temp2->next;

} else {

Int sum = temp1->coefficient + temp2->coefficient;

If (sum != 0) {

insertTerm(&result, sum, temp1->exponent);

Temp1 = temp1->next;

Temp2 = temp2->next;

While (temp1 != NULL) {

insertTerm(&result, temp1->coefficient, temp1->exponent);

temp1 = temp1->next;

While (temp2 != NULL) {

insertTerm(&result, temp2->coefficient, temp2->exponent);

temp2 = temp2->next;

Return result;

// Function to subtract two polynomials

Struct Node* subtractPolynomials(struct Node* poly1, struct Node* poly2) {


Struct Node* result = NULL;

Struct Node* temp1 = poly1;

Struct Node* temp2 = poly2;

While (temp1 != NULL && temp2 != NULL) {

If (temp1->exponent > temp2->exponent) {

insertTerm(&result, temp1->coefficient, temp1->exponent);

temp1 = temp1->next;

} else if (temp1->exponent < temp2->exponent) {

insertTerm(&result, -temp2->coefficient, temp2->exponent);

temp2 = temp2->next;

} else {

Int diff = temp1->coefficient – temp2->coefficient;

If (diff != 0) {

insertTerm(&result, diff, temp1->exponent);

Temp1 = temp1->next;

Temp2 = temp2->next;

While (temp1 != NULL) {

insertTerm(&result, temp1->coefficient, temp1->exponent);

temp1 = temp1->next;

While (temp2 != NULL) {


insertTerm(&result, -temp2->coefficient, temp2->exponent);

temp2 = temp2->next;

Return result;

// Function to multiply two polynomials

Struct Node* multiplyPolynomials(struct Node* poly1, struct Node* poly2) {

Struct Node* result = NULL;

Struct Node* temp1 = poly1;

While (temp1 != NULL) {

Struct Node* temp2 = poly2;

While (temp2 != NULL) {

Int coeff = temp1->coefficient * temp2->coefficient;

Int exp = temp1->exponent + temp2->exponent;

insertTerm(&result, coeff, exp);

temp2 = temp2->next;

Temp1 = temp1->next;

Return result;

Int main() {
Struct Node* poly1 = NULL;

Struct Node* poly2 = NULL;

Struct Node* result = NULL;

// Create first polynomial: 5x^3 + 4x^2 + 2x + 3

insertTerm(&poly1, 5, 3);

insertTerm(&poly1, 4, 2);

insertTerm(&poly1, 2, 1);

insertTerm(&poly1, 3, 0);

// Create second polynomial: 3x^3 + 2x^2 + x + 1

insertTerm(&poly2, 3, 3);

insertTerm(&poly2, 2, 2);

insertTerm(&poly2, 1, 1);

insertTerm(&poly2, 1, 0);

// Display the polynomials

Printf(“First Polynomial: “);

displayPolynomial(poly1);

printf(“Second Polynomial: “);

displayPolynomial(poly2);

// Add the polynomials

Result = addPolynomials(poly1, poly2);

Printf(“Sum of Polynomials: “);

displayPolynomial(result);
// Subtract the polynomials

Result = subtractPolynomials(poly1, poly2);

Printf(“Difference of Polynomials: “);

displayPolynomial(result);

// Multiply the polynomials

Result = multiplyPolynomials(poly1, poly2);

Printf(“Product of Polynomials: “);

displayPolynomial(result);

return 0;

Output:

First Polynomial: 5x^3 + 4x^2 + 2x + 3

Second Polynomial: 3x^3 + 2x^2 + x + 1

Sum of Polynomials: 8x^3 + 6x^2 + 3x + 4

Difference of Polynomials: 2x^3 + 2x^2 + x + 2

Product of Polynomials: 15x^6 + 26x^5 + 19x^4 + 11x^3 + 5x^2 + 3x

You might also like