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

Data Structures Lab File

The document is an index of assignments from a data structures lab file submitted for a bachelor's degree in computer science. It lists 17 assignments related to implementing various data structures and algorithms using arrays, linked lists, stacks, queues, trees, and graphs. The assignments include operations like traversal, insertion, deletion, searching and sorting on arrays and different types of linked lists, as well as implementing stacks, queues, binary search trees and graph traversal algorithms.

Uploaded by

harsh.2116403221
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Data Structures Lab File

The document is an index of assignments from a data structures lab file submitted for a bachelor's degree in computer science. It lists 17 assignments related to implementing various data structures and algorithms using arrays, linked lists, stacks, queues, trees, and graphs. The assignments include operations like traversal, insertion, deletion, searching and sorting on arrays and different types of linked lists, as well as implementing stacks, queues, binary search trees and graph traversal algorithms.

Uploaded by

harsh.2116403221
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 92

DATA STRUCTURES LAB FILE

ICT-255
Submitted in partial fulfilment of the requirements for the award of
the degree of
B.Tech.
in
COMPUTER SCIENCE

SUBMITTED TO: SUBMITTED BY:


DR. REENA GUPTA NAME – HARSH GOYAL
ASSOCIATE PROFESSOR ENROLLMENT NO.-02116403221

UNIVERSITY SCHOOL OF INFORMATION COMMUNICATION AND TECHNOLOGY


GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY

JANUARY - 2023
INDEX
S.No Assignment Name Date Remarks
.
1. Implement operations (traverse, insert,
delete, linear search, selection sort) on an
array.
2. Implement insertion and deletion (at the
beginning, at specified location, at the
end) on single linked list.
3. Implement insertion and deletion (at the
beginning, at specified location, at the
end) on circular single linked list.
4. Implement insertion and deletion (at the
beginning, at specified location, at the
end) on double linked list.
5. Implement insertion and deletion (at the
beginning, at specified location, at the
end) on circular double linked list
6. Write a program to count the number of
nodes & reverse the single linked list.
7. Write a program to merge two sorted
linked list and display the final sorted
linked list.
8. Implement addition of two polynomial
expressions using singly linked list.
9. Implement operations (push, pop) on a
stack using arrays. Check the status of the
stack whether there is underflow or
overflow.
10. .Implement the conversion of infix
notation to postfix notation.
11. .Implement the conversion of infix
notation to postfix notation.
12. .Implement binary search using recursion.
13. .Implement operations (enqueue,
dequeue) on a queue using arrays. Check
the status of the queue whether it is
empty or full.
14. Implement circular queue using arrays
and linked list.
15. .Implement stacks and queues using
linked list.
16. .Implement Sparse Array.
17. .Implement operations on Binary Search
Tree (Insertion, Deletion, Search,
Traversals (using recursion)- Inorder,
Preorder, Postorder).
18. .Implement traversals on Binary Search
Tree (using stacks) - Inorder, Preorder,
Postorder).
19. .Implement graph traversal (DFS & BFS)
20. Make a menu driven program to perform
various sorting techniques (insertion,
shell, merge, heap, bubble, quick).
1.Implement operations (traverse, insert, delete, linear search,
selection sort) on an array
#include <stdio.h>
#include <stdbool.h>

// Experiment 1: Implement operations (traverse, insert, delete, linear


search, selection sort) on an array.

void display(int A[], int size)


{
if (size == 0)
{
printf("Array is empty\n");
return;
}

printf("Array is: ");


for (int i = 0; i < size; i++)
{
printf("%d ", A[i]);
}
printf("\nSize of array: %d\n", size);
}

bool insertAtBegin(int A[], int size, int maxSize, int item) // Returns true
if inserted successfully
{
if (size == maxSize)
{
printf("Array is full\n");
return false;
}

// Moving all elements forward


for (int i = size; i > 0; i--)
{
A[i] = A[i - 1];
}
A[0] = item; // Inserting element
printf("Inserted Successfully\n");
return true;
}

bool insertAtPos(int A[], int size, int maxSize, int pos, int item) // Returns
true if inserted successfully
{
if (size == maxSize)
{
printf("Array is full\n");
return false;
}
if (size < pos || pos < 0)
{
printf("Invalid Position");
return false;
}

// Moving elements from given position to end one space forward


for (int i = size; i > pos; i--)
{
A[i] = A[i - 1];
}
A[pos] = item; // Inserting element
printf("Inserted Successfully\n");
return true;
}

bool insertAtLast(int A[], int size, int maxSize, int item) // Returns true if
inserted successfully
{
if (size == maxSize)
{
printf("Array is full\n");
return false;
}

A[size] = item; // Inserting element


printf("Inserted Successfully\n");
return true;
}

bool deleteAtBegin(int A[], int size, int item) // Returns true if deleted
successfully
{
if (size == 0)
{
printf("Array is empty\n");
return false;
}

for (int i = 0; i < size - 1; i++)


{
A[i] = A[i + 1];
}
printf("Deleted Successfully\n");
return true;
}

bool deleteAtPos(int A[], int size, int pos) // Returns true if deleted
successfully
{
if (size == 0)
{
printf("Array is empty\n");
return false;
}
if (size < pos || pos < 0)
{
printf("Invalid Position");
return false;
}

for (int i = pos; i < size - 1; i++)


{
A[i] = A[i + 1];
}

printf("Deleted Successfully\n");
return true;
}

bool deleteAtLast(int A[], int size, int item) // Returns true if deleted
successfully
{
if (size == 0)
{
printf("Array is empty\n");
return false;
}

printf("Deleted Successfully\n");
return true;
}

int linearSearch(int A[], int size, int item)


{
for (int i = 0; i < size; i++)
{
if (item == A[i])
{
return i; // Return index of element
}
}
return -1; // Return -1 if element not found
}

void selectionSort(int A[], int size) // Modifies the array directly since
call by address
{
int i, j, k;
for (i = 0; i < size - 1; i++)
{
for (j = k = i; j < size; j++)
{
if (A[j] < A[k])
k = j;
}
int temp = A[k];
A[k] = A[i];
A[i] = temp;
}
printf("Done!\n");
}

int main()
{
int maxSize, curSize = 0;
printf("Enter max size of array: ");
scanf("%d", &maxSize);

if (maxSize <= 0)
{
printf("An array cant have negative or zero length");
return 0;
}

bool exit = false, check;


int A[maxSize];
while (!exit)
{
int ch;
printf("\n1.Display Array\n2.Insert\n3.Delete\n4.Search\n5.Sort\
n6.Exit\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: // Display
{
display(A, curSize);
break;
}
case 2: // Insert
{
int item, x;
printf("Enter item: ");
scanf("%d", &item);
if (curSize == 0) // If empty array then directly insert element
{
check = insertAtBegin(A, curSize, maxSize, item);
if (check) // Update size if successfully inserted
curSize++;
display(A,curSize);
break;
}
printf("1.Begin\n");
printf("2.End\n");
if (curSize != 1)
printf("3.Locn\n");
printf("Enter your choice: ");
scanf("%d", &x);
if (x == 1)
{
check = insertAtBegin(A, curSize, maxSize, item);
}
else if (x == 2)
{
check = insertAtLast(A, curSize, maxSize, item);
}
else if (curSize != 1 && x == 3)
{
int locn;
printf("Enter locn: ");
scanf("%d", &locn);
check = insertAtPos(A, curSize, maxSize, locn, item);
}
else
{
check = false;
printf("Invalid Choice\n");
}
if (check) // Update size if successfully inserted
curSize++;
display(A,curSize);
break;
}
case 3: // Delete
{
int x;
if (curSize <= 1)
{
check = deleteAtBegin(A, curSize, maxSize);
if (check) // Update size if successfully deleted
curSize--;
break;
}
printf("1.Begin\n");
printf("2.End\n");
if (curSize > 2)
printf("3.Locn\n");
printf("Enter your choice: ");
scanf("%d", &x);
if (x == 1)
{
check = deleteAtBegin(A, curSize, maxSize);
}
else if (x == 2)
{
check = deleteAtLast(A, curSize, maxSize);
}
else if (curSize >= 3 && x == 3)
{
int locn;
printf("Enter locn: ");
scanf("%d", &locn);
check = deleteAtPos(A, curSize, locn);
}
else
{
check = false;
printf("Invalid Choice\n");
}
if (check) // Update size if successfully deleted
curSize--;
display(A,curSize);
break;
}
case 4: // Search
{
int item, x;
printf("Enter item: ");
scanf("%d", &item);
int index = linearSearch(A, curSize, item);
if (index == -1)
printf("Element Not Found\n");
else
printf("Element is at index %d\n", index);
display(A,curSize);
break;
}
case 5: // Sort
{
selectionSort(A, curSize);
display(A,curSize);
break;
}
default: // For Invalid Choice
{
exit = true;
break;
}
}
}
return 0;
}

OUTPUT

2. Implement insertion and deletion (at the beginning, at specified location, at


the end) on single linked list.
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>

// Experiment 2: Implement insertion and deletion (at the beginning, at


specified location, at the end) on single linked list.

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

void display(struct node *head) {


if (head == NULL) {
printf("Linked List is empty!\n");
return;
}

struct node *temp = head;


while (temp != NULL && temp->next != NULL) {
printf("%d -> ", temp->val);
temp = temp->next;
}
printf("%d\n",temp->val);
}

struct node *insertAtBegin(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->next = head;
printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *insertAtEnd(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->next = NULL;

if (head == NULL) {
printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *temp = head;


while (temp->next != NULL)
temp = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *insertAtPos(struct node *head, int val, int loc) { // To insert
after a certain node with given value
if (head == NULL) {
printf("No such node with given loc\n");
return NULL;
}
struct node *temp = head;
while (temp != NULL && temp->val != loc) {
temp = temp->next;
}

if (temp == NULL) {
printf("No such node with given loc\n");
display(head);
return head;
}

struct node *p = (struct node *)malloc(sizeof(struct node));


p->val = val;
p->next = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *deleteFromBegin(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head;


head = head->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromEnd(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p != NULL && p->next != NULL) {
q = p;
p = p->next;
}

if (p == head) {
free(p);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}

free(p);
q->next = NULL;
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromPos(struct node *head, int loc) { // Delete 1st node
with value equal to given loc
if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p != NULL && p->val != loc) {
q = p;
p = p->next;
}

if (p == NULL) {
printf("No such node with value as given loc\n");
display(head);
return head;
}

if (p == head) return deleteFromBegin(head);

q->next = p->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

int main() {
struct node *head = NULL;
int ch;
bool exit = false;
while (exit == false) {
printf("1. Display\n2. Insert\n3. Delete\n4. Exit\nEnter your choice:
");
scanf("%d", &ch);
printf("\n");
switch (ch) {
case 1:
display(head);
break;
case 2: {
int val;
printf("Enter value: ");
scanf("%d", &val);
if (head == NULL) {
head = insertAtBegin(head, val);
break;
}

int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = insertAtBegin(head, val);
else if (ch == 2) head = insertAtEnd(head, val);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node after which to insert):
");
scanf("%d", &loc);
head = insertAtPos(head, val, loc);
} else printf("Invalid choice\n");
break;
}
case 3: {
if (head == NULL) {
printf("Linked List is already empty");
break;
}
int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = deleteFromBegin(head);
else if (ch == 2) head = deleteFromEnd(head);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node to delete): ");
scanf("%d", &loc);
head = deleteFromPos(head, loc);
} else printf("Invalid choice\n");
break;
}
case 4:
exit = true;
printf("Thank You! Created by Harsh Goyal");
break;
default:
printf("Invalid Choice");
break;
}
printf("\n");
}

return 0;
}
OUTPUT

3. Implement insertion and deletion (at the beginning, at specified location, at


the end) on circular single linked list
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>

// Experiment 3: Implement insertion and deletion (at the beginning, at


specified location, at the end) on circular single linked list

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

void display(struct node *head) {


if (head == NULL) {
printf("Linked List is empty!\n");
return;
}

printf("%d ", head->val);


struct node *temp = head->next;
while (temp != head) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
}

struct node *insertAtBegin(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;

if (head == NULL) {
p->next = p;
printf("Inserted Successfully\n");
display(p);
return p;
}

p->next = head;
struct node *temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *insertAtEnd(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;

if (head == NULL) {
p->next = p;
printf("Inserted Successfully\n");
display(p);
return p;
}

p->next = head;
struct node *temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *insertAtPos(struct node *head, int val, int loc) { // To insert
after a certain node with given value
if (head == NULL) {
printf("No such node with given loc\n");
return NULL;
}

struct node *temp = head;


while (temp->next != head && temp->val != loc)
temp = temp->next;

if (temp->next == head && temp->val != loc) {


printf("No such node with given loc\n");
display(head);
return head;
}

struct node *p = (struct node *)malloc(sizeof(struct node));


p->val = val;
p->next = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *deleteFromBegin(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

if (head->next == head) {
free(head);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}

struct node *p = head, *temp = head;


while (temp->next != head)
temp = temp->next;
temp->next = head->next;
head = head->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}
struct node *deleteFromEnd(struct node *head) {
if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p->next != head) {
q = p;
p = p->next;
}

if (p == head) { // Only one node


free(p);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}

free(p);
q->next = head;
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromPos(struct node *head, int loc) { // Delete 1st node
with value equal to given loc
if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p->next != head && p->val != loc) {
q = p;
p = p->next;
}

if (p->next == head && p->val != loc) {


printf("No such node with value as given loc\n");
display(head);
return head;
}

if (p == head) return deleteFromBegin(head);


q->next = p->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

int main() {
struct node *head = NULL;
int n;
int ch;
bool exit = false;
while (exit == false) {
printf("1. Display\n2. Insert\n3. Delete\n4. Exit\nEnter your choice:
");
scanf("%d", &ch);
printf("\n");
switch (ch) {
case 1:
display(head);
break;
case 2: {
int val;
printf("Enter value: ");
scanf("%d", &val);
if (head == NULL) {
head = insertAtBegin(head, val);
break;
}

int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = insertAtBegin(head, val);
else if (ch == 2) head = insertAtEnd(head, val);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node after which to insert):
");
scanf("%d", &loc);
head = insertAtPos(head, val, loc);
} else printf("Invalid choice\n");
break;
}
case 3: {
if (head == NULL) {
printf("Linked List is already empty");
break;
}
int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = deleteFromBegin(head);
else if (ch == 2) head = deleteFromEnd(head);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node to delete): ");
scanf("%d", &loc);
head = deleteFromPos(head, loc);
} else printf("Invalid choice\n");
break;
}
case 4:
exit = true;
printf("Thank You! Created by Harsh Goyal");
break;
default:
printf("Invalid Choice\n");
break;
}
printf("\n");
}

return 0;
}
OUTPUT

4. Implement insertion and deletion (at the beginning, at specified location, at


the end) on double linked list.
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>

// Experiment 4: Implement insertion and deletion (at the beginning, at


specified location, at the end) on double linked list.

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

void display(struct node *head) {


if (head == NULL) {
printf("Linked List is empty!\n");
return;
}

struct node *temp = head;


while (temp != NULL && temp->next != NULL) {
printf("%d <--> ", temp->val);
temp = temp->next;
}
printf("%d\n",temp->val);
}

struct node *insertAtBegin(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->prev = NULL;
p->next = head;
printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *insertAtEnd(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->next = p->prev = NULL;

if (head == NULL) {
printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *temp = head;


while (temp->next != NULL)
temp = temp->next;
temp->next = p;
p->prev = temp;

printf("Inserted Successfully\n");
display(head);
return head;
}
struct node *insertAtPos(struct node *head, int val, int loc) { // To insert
after a certain node with given value
if (head == NULL) {
printf("No such node with given loc\n");
return NULL;
}

struct node *temp = head;


while (temp != NULL && temp->val != loc) {
temp = temp->next;
}

if (temp == NULL) {
printf("No such node with given loc\n");
display(head);
return head;
}

struct node *p = (struct node *)malloc(sizeof(struct node));


p->val = val;
p->next = temp->next;
p->prev = temp;
if (temp->next != NULL) temp->next->prev = p;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *deleteFromBegin(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head;


head = head->next;
if (head != NULL) head->prev = NULL;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromEnd(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p != NULL && p->next != NULL) {
q = p;
p = p->next;
}

if (p == head) {
free(p);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}

free(p);
q->next = NULL;
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromPos(struct node *head, int loc) { // Delete 1st node
with value equal to given loc
if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p != NULL && p->val != loc) {
q = p;
p = p->next;
}

if (p == NULL) {
printf("No such node with value as given loc\n");
display(head);
return head;
}

if (p == head) return deleteFromBegin(head);

q->next = p->next;
if (p->next != NULL) p->next->prev = q;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

int main() {
struct node *head = NULL;
int ch;
bool exit = false;
while (exit == false) {
printf("1. Display\n2. Insert\n3. Delete\n4. Exit\nEnter your choice:
");
scanf("%d", &ch);
printf("\n");
switch (ch) {
case 1:
display(head);
break;
case 2: {
int val;
printf("Enter value: ");
scanf("%d", &val);
if (head == NULL) {
head = insertAtBegin(head, val);
break;
}

int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = insertAtBegin(head, val);
else if (ch == 2) head = insertAtEnd(head, val);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node after which to insert):
");
scanf("%d", &loc);
head = insertAtPos(head, val, loc);
} else printf("Invalid choice\n");
break;
}
case 3: {
if (head == NULL) {
printf("Linked List is already empty");
break;
}
int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = deleteFromBegin(head);
else if (ch == 2) head = deleteFromEnd(head);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node to delete): ");
scanf("%d", &loc);
head = deleteFromPos(head, loc);
} else printf("Invalid choice\n");
break;
}
case 4:
exit = true;
printf("Thank You! Created by Harsh Goyal");
break;
default:
printf("Invalid Choice");
break;
}
printf("\n");
}

return 0;
}

5. Implement insertion and deletion (at the beginning, at specified location, at


the end) on circular double linked list.
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>

// Experiment 5: Implement insertion and deletion (at the beginning, at


specified location, at the end) on circular double linked list.

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

void display(struct node *head) {


if (head == NULL) {
printf("Linked List is empty!\n");
return;
}

printf("%d ", head->val);


struct node *temp = head->next;
while (temp != head) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
}

struct node *insertAtBegin(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;

if (head == NULL) {
p->next = p;
p->prev = p;
printf("Inserted Successfully\n");
display(p);
return p;
}

head->prev->next = p;
p->prev = head->prev;
head->prev = p;
p->next = head;

printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *insertAtEnd(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;

if (head == NULL) {
p->next = p;
printf("Inserted Successfully\n");
display(p);
return p;
}

head->prev->next = p;
p->prev = head->prev;
head->prev = p;
p->next = head;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *insertAtPos(struct node *head, int val, int loc) { // To insert
after a certain node with given value
if (head == NULL) {
printf("No such node with given loc\n");
return NULL;
}

struct node *temp = head;


while (temp->next != head && temp->val != loc)
temp = temp->next;

if (temp->next == head && temp->val != loc) {


printf("No such node with given loc\n");
display(head);
return head;
}

struct node *p = (struct node *)malloc(sizeof(struct node));


p->val = val;
p->next = temp->next;
p->prev = temp;
p->next->prev = p;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *deleteFromBegin(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

if (head->next == head) {
free(head);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}
struct node *p = head;
head->prev->next = head->next;
head->next->prev = head->prev;
head = head->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromEnd(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

if (head->next == head) { // Only one node


free(head);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}

struct node *p = head->prev;


head->prev = p->prev;
p->prev->next = head;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromPos(struct node *head, int loc) { // Delete 1st node
with value equal to given loc
if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p->next != head && p->val != loc) {
q = p;
p = p->next;
}

if (p->next == head && p->val != loc) {


printf("No such node with value as given loc\n");
display(head);
return head;
}

if (p == head) return deleteFromBegin(head);

q->next = p->next;
p->next->prev = q;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

int main() {
struct node *head = NULL;
int n;
int ch;
bool exit = false;
while (exit == false) {
printf("1. Display\n2. Insert\n3. Delete\n4. Exit\nEnter your choice:
");
scanf("%d", &ch);
printf("\n");
switch (ch) {
case 1:
display(head);
break;
case 2: {
int val;
printf("Enter value: ");
scanf("%d", &val);
if (head == NULL) {
head = insertAtBegin(head, val);
break;
}

int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = insertAtBegin(head, val);
else if (ch == 2) head = insertAtEnd(head, val);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node after which to insert):
");
scanf("%d", &loc);
head = insertAtPos(head, val, loc);
} else printf("Invalid choice\n");
break;
}
case 3: {
if (head == NULL) {
printf("Linked List is already empty");
break;
}
int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = deleteFromBegin(head);
else if (ch == 2) head = deleteFromEnd(head);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node to delete): ");
scanf("%d", &loc);
head = deleteFromPos(head, loc);
} else printf("Invalid choice\n");
break;
}
case 4:
exit = true;
printf("Thank You! Created by Harsh Goyal");
break;
default:
printf("Invalid Choice\n");
break;
}
printf("\n");
}

return 0;
}
OUTPUT

6. Write a program to count the number of nodes & reverse the single linked
list.
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
// Experiment 6: Write a program to count the number of nodes & reverse the
single linked list.

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

void display(struct node *head) {


if (head == NULL) {
printf("Linked List is empty!\n");
return;
}

struct node *temp = head;


while (temp != NULL && temp->next != NULL) {
printf("%d -> ", temp->val);
temp = temp->next;
}
printf("%d\n",temp->val);
}

struct node *insertAtBegin(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->next = head;
printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *insertAtEnd(struct node *head, int val) {


struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->next = NULL;

if (head == NULL) {
printf("Inserted Successfully\n");
display(p);
return p;
}

struct node *temp = head;


while (temp->next != NULL)
temp = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *insertAtPos(struct node *head, int val, int loc) { // To insert
after a certain node with given value
if (head == NULL) {
printf("No such node with given loc\n");
return NULL;
}

struct node *temp = head;


while (temp != NULL && temp->val != loc) {
temp = temp->next;
}

if (temp == NULL) {
printf("No such node with given loc\n");
display(head);
return head;
}

struct node *p = (struct node *)malloc(sizeof(struct node));


p->val = val;
p->next = temp->next;
temp->next = p;

printf("Inserted Successfully\n");
display(head);
return head;
}

struct node *deleteFromBegin(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head;


head = head->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromEnd(struct node *head) {


if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p != NULL && p->next != NULL) {
q = p;
p = p->next;
}

if (p == head) {
free(p);
printf("Deleted Successfully\n");
display(NULL);
return NULL;
}

free(p);
q->next = NULL;
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *deleteFromPos(struct node *head, int loc) { // Delete 1st node
with value equal to given loc
if (head == NULL) {
printf("Linked List is already empty");
return head;
}

struct node *p = head, *q = NULL;


while (p != NULL && p->val != loc) {
q = p;
p = p->next;
}

if (p == NULL) {
printf("No such node with value as given loc\n");
display(head);
return head;
}

if (p == head) return deleteFromBegin(head);

q->next = p->next;
free(p);
printf("Deleted Successfully\n");
display(head);
return head;
}

struct node *reverse(struct node * head) {


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

struct node *p = NULL, *q = head, *r = head->next;


while (q != NULL) {
q->next = p;
p = q;
q = r;
if (r != NULL) r = r->next;
}

return p;
}

int countNodes(struct node * head) {


int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}

int main() {
struct node *head = NULL;
int ch;
bool exit = false;
while (exit == false) {
printf("1. Display\n2. Insert\n3. Delete\n4. Reverse\n5. Count Nodes\
n6. End\nEnter your choice: ");
scanf("%d", &ch);
printf("\n");
switch (ch) {
case 1:
display(head);
break;
case 2: {
int val;
printf("Enter value: ");
scanf("%d", &val);
if (head == NULL) {
head = insertAtBegin(head, val);
break;
}
int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = insertAtBegin(head, val);
else if (ch == 2) head = insertAtEnd(head, val);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node after which to insert):
");
scanf("%d", &loc);
head = insertAtPos(head, val, loc);
} else printf("Invalid choice\n");
break;
}
case 3: {
if (head == NULL) {
printf("Linked List is already empty");
break;
}
int ch;
printf("1. Begin\n2. End\n3. Locn\nEnter your choice: ");
scanf("%d", &ch);
if (ch == 1) head = deleteFromBegin(head);
else if (ch == 2) head = deleteFromEnd(head);
else if (ch == 3) {
int loc;
printf("Enter locn(value of node to delete): ");
scanf("%d", &loc);
head = deleteFromPos(head, loc);
} else printf("Invalid choice\n");
break;
}
case 4:
head = reverse(head);
display(head);
break;
case 5:
printf("There are %d node(s) in the linked list\
n",countNodes(head));
break;
case 6:
exit = true;
printf("Thank You! Created by Harsh Goyal");
break;
default:
printf("Invalid Choice");
break;
}
printf("\n");
}

return 0;
}
OUTPUT

7. Write a program to merge two sorted linked list and display the final sorted
linked list.
#include <stdio.h>
#include <malloc.h>

// Experiment 7: Write a program to merge two sorted linked list and display
the final sorted linked list.

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

void display(struct node *head) {


if (head == NULL) {
printf("Linked List is empty!\n");
return;
}

struct node *temp = head;


while (temp != NULL && temp->next != NULL) {
printf("%d -> ", temp->val);
temp = temp->next;
}
printf("%d\n",temp->val);
}

struct node* copy(struct node * p) {


if (p==NULL) return NULL;

struct node* head = (struct node*)malloc(sizeof(struct node));


head->val = p->val;
head->next = NULL;
p = p->next;
struct node* last = head;

while (p!=NULL) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->val = p->val;
temp->next = NULL;
p = p->next;
last->next = temp;
last = last->next;
}

return head;
}

struct node * merge(struct node* p, struct node* q) {


if (p == NULL || q == NULL) return copy(p != NULL ? p : q);

struct node* head = (struct node*)malloc(sizeof(struct node));


head->next = NULL;
if (p->val <= q->val) {
head->val = p->val;
p=p->next;
} else {
head->val = q->val;
q = q->next;
}

struct node* last = head;


while (p != NULL && q != NULL) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->next = NULL;
if (p->val <= q->val) {
temp->val = p->val;
p=p->next;
} else {
temp->val = q->val;
q = q->next;
}
last->next = temp;
last = last->next;
}

if (p != NULL) {
last->next = copy(p);
}
if (q != NULL) {
last->next = copy(q);
}
return head;
}

struct node* create() {


struct node* last,*head;
last = head = NULL;

int ch=1;
while (ch == 1) {
int val;
printf("Enter value: ");
scanf("%d",&val);

if (last != NULL && last->val > val) {


printf("Value should be greater than value of last node\n");
display(head);
continue;
}

struct node* q = (struct node*)malloc(sizeof(struct node));


q->val = val;
q->next = NULL;

if (last == NULL) {
last = head = q;
} else {
last->next = q;
last = q;
}

display(head);

printf("Do u want to enter more elements(1 for yes): ");


scanf("%d",&ch);
}
return head;
}

int main() {
printf("For 1st linked list..\n");
struct node* head1= create();

printf("\nFor 2nd linked list..\n");


struct node* head2 = create();

struct node* head = merge(head1,head2);


printf("1st linked list: ");
display(head1);
printf("2nd linked list: ");
display(head2);
printf("\nMerged linked list: ");
display(head);

return 0;
}
OUTPUT

8. Implement addition of two polynomial expressions using singly linked list.


#include <stdio.h>
#include <malloc.h>

// Experiment 8: Implement addition of two polynomial expressions using singly


linked list.

struct node {
int coeff,exp;
struct node *next;
};

void display(struct node* head) {


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

printf("(%d)x^(%d) ",head->coeff,head->exp);
head = head->next;
while (head != NULL) {
if (head->exp == 0) printf("+ (%d) ",head->coeff);
else printf("+ (%d)x^(%d) ",head->coeff,head->exp);
head = head->next;
}
printf("\n");
}

struct node* addition(struct node* x1, struct node* x2) {


if (x1 == NULL || x2 == NULL) return (x1 != NULL ? x1 : x2);

struct node* head=(struct node*)malloc(sizeof(struct node));


head->next = NULL;
if (x1->exp > x2->exp) {
head->exp = x1->exp;
head->coeff = x1->coeff;
x1 = x1->next;
} else if (x1->exp < x2->exp) {
head->exp = x2->exp;
head->coeff = x2->coeff;
x2 = x2->next;
} else {
head->exp = x1->exp;
head->coeff = x1->coeff+x2->coeff;
x1 = x1->next;
x2 = x2->next;
}

struct node* last = head;


while (x1 != NULL && x2 != NULL) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->next = NULL;

if (x1->exp > x2->exp) {


temp->exp = x1->exp;
temp->coeff = x1->coeff;
x1 = x1->next;
} else if (x1->exp < x2->exp) {
temp->exp = x2->exp;
temp->coeff = x2->coeff;
x2 = x2->next;
} else {
temp->exp = x1->exp;
temp->coeff = x1->coeff+x2->coeff;
x1 = x1->next;
x2 = x2->next;
}

last->next = temp;
last = last->next;
}
if (x1 != NULL) {
while (x1 != NULL) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->next = NULL;
temp->exp = x1->exp;
temp->coeff = x1->coeff;
x1 = x1->next;

last->next = temp;
last = last->next;
}
} else if (x2 != NULL) {
while (x2 != NULL) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->next = NULL;
temp->exp = x2->exp;
temp->coeff = x2->coeff;
x2 = x2->next;

last->next = temp;
last = last->next;
}
}

return head;
}

struct node* create() {


struct node* head,*last;
head=last=NULL;

int ch=1;
while (ch == 1) {
int exp;
printf("Enter exponent: ");
scanf("%d",&exp);

if (last != NULL && last->exp <= exp) {


printf("Pls enter expression in decreasing exponent\n");
display(head);
continue;
}

int coeff;
printf("Enter coefficient: ");
scanf("%d",&coeff);

struct node* q = (struct node*)malloc(sizeof(struct node));


q->exp = exp;
q->coeff = coeff;
q->next = NULL;

if (last == NULL) {
last = head = q;
} else {
last->next = q;
last = q;
}

display(head);

printf("Do u want to enter more elements(1 for yes): ");


scanf("%d",&ch);
}
return head;
}

int main() {
printf("For 1st polynomial..\n");
struct node* head1= create();

printf("\nFor 2nd polynomial..\n");


struct node* head2 = create();

struct node* head = addition(head1,head2);


printf("\n\nNow adding both polynomials\n");
printf("Polynomial 1: ");
display(head1);
printf("Polynomial 2: ");
display(head2);
printf("\nAfter addition: ");
display(head);

return 0;
}
OUTPUT
9. . Implement operations (push, pop) on a stack using arrays. Check the status
of the stack whether there is underflow or overflow.
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>

// Experiment 9: Implement operations (push, pop) on a stack using arrays.


Check the status of the stack whether there is underflow or overflow.

struct stack {
int *stk;
int size;
int top;
};

bool isEmpty(struct stack *s) {


return (s->top == -1);
}

bool isFull(struct stack *s) {


return (s->top == s->size - 1);
}

void push(struct stack *s,int x) {


if (isFull(s)) {
printf("Stack Overflow\n");
return;
}

s->top++;
s->stk[s->top] = x;
}

int pop(struct stack *s) {


if (isEmpty(s)) {
printf("Stack Underflow\n");
return -1;
}

s->top--;
return s->stk[s->top+1];
}

int top(struct stack *s) {


if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}

return s->stk[s->top];
}

void display(struct stack *s) {


if (isEmpty(s)) {
printf("\nStack is empty\n");
return;
}

printf("\nStack looks like below: \n");


int i=s->top;
printf("%d <- Top\n",s->stk[i--]);
while (i>=0) {
printf("%d\n",s->stk[i]);
i--;
}
}

int main() {
int n;
printf("Enter max size of stack: ");
scanf("%d",&n);
struct stack s;
s.stk = (int *)malloc(sizeof(int)*n);
s.top=-1;
s.size=n;

bool exit = false;


while (!exit) {
printf("\nMenu: \n1. Push\n2. Pop\n3. Top\n4. Display\n5. Exit\nEnter
your choice: ");
int ch;
scanf("%d",&ch);
switch (ch) {
case 1: {
printf("Enter an element: ");
int elem;
scanf("%d",&elem);
push(&s,elem);
display(&s);
break;
}
case 2: {
int elem = pop(&s);
if (elem != -1) {
printf("\nPopped element is %d\n",elem);
display(&s);
}
break;
}
case 3: {
int elem = top(&s);
if (elem != -1)
printf("\nTopmost element of stack: %d\n",elem);
break;
}
case 4: {
display(&s);
break;
}
case 5: {
exit = true;
break;
}
default: {
printf("Invalid option.\n");
break;
}
}
}

return 0;
}
OUTPUT

10. Implement the conversion of infix notation to postfix notation.


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

// Experiment 10: Implement the conversion of infix notation to postfix


notation.

struct stack {
char *stk;
int size;
int top;
};

bool isEmpty(struct stack *s) {


return (s->top == -1);
}

bool isFull(struct stack *s) {


return (s->top == s->size - 1);
}

void push(struct stack *s,char x) {


if (isFull(s)) {
return;
}

s->top++;
s->stk[s->top] = x;
}

char pop(struct stack *s) {


if (isEmpty(s)) {
return '?'; // ? is just a symbol to know that stack is empty
}

s->top--;
return s->stk[s->top+1];
}

char top(struct stack *s) {


if (isEmpty(s)) {
return '?'; // ? is just a symbol to know that stack is empty
}

return s->stk[s->top];
}

int isOperator(char x) { // This function is used in checking infix expression


if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^') return 1;
return 0;
}

int checkInfixExpression(char *infix) {


int noOfOperators=0,noOfOperands=0,noOfOpenBrackets=0;
for (int i=0;infix[i] != '\0';i++) {
if (isOperator(infix[i])) {
if (i == 0 || infix[i+1] == '\0') return 0; // If last or first
char is operator
if (isOperator(infix[i+1])) return 0; // If next char is operator
if (infix[i-1] == '(' || infix[i+1] == ')') return 0; //
Unnecessary opening bracket before or closing bracket after
noOfOperators++;
} else if (infix[i] == '(')
noOfOpenBrackets++;
else if (infix[i] == ')') {
noOfOpenBrackets--;
if (noOfOpenBrackets < 0) return 0;
} else
noOfOperands++;
}
if (noOfOpenBrackets > 0 || noOfOperands != noOfOperators+1) return 0;
return 1;
}

int isOperand(char x) {
if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^' || x =='(' ||
x == ')') return 0;
return 1;
}

int precedence(char x,int inStack) {


if (x == '+' || x == '-') return 1;
if (x == '*' || x == '/') return 2;
if (x == '^') return 3;
if (x == '(') return inStack ? 0:4;
if (x == ')') return 0;
return -1;
}

void convert(char *infix,char *postfix) {


struct stack s;
s.stk = (char *)malloc(sizeof(char)*100);
s.top=-1;
s.size=100;
int i=0,j=0;
while (infix[i] != '\0') {
if (isOperand(infix[i]))
postfix[j++] = infix[i++];
else {
char stackTop = top(&s);
if (precedence(infix[i],0) > precedence(stackTop,1))
push(&s,infix[i++]);
else {
if (precedence(infix[i],0) == precedence(stackTop,1) &&
precedence(infix[i],0) == 0) {
pop(&s);
i++;
} else {
postfix[j++] = pop(&s);
}
}
}
}
while (!isEmpty(&s))
postfix[j++] = pop(&s);
postfix[j] = '\0';
}

void display(char *x) {


for (int i=0;x[i] != '\0';i++) {
printf("%c",x[i]);
}
}

int main() {
char infix[100],postfix[100],temp;
printf("Enter your infix expression(enter '?' whenever to stop): ");

int i=0;
for (;i<99;i++) {
// printf("Input %d: ",i+1);
scanf(" %c",&temp);
if (temp == '?') break;
infix[i] = temp;
}
if (i == 99) printf("You have reached max size of array");
infix[i] = '\0';

int ch = checkInfixExpression(infix);
if (ch == 0) {
printf("Entered infix expression is not valid\n");
return 0;
}
convert(infix,postfix);

printf("Given infix expression: ");


display(infix);
printf("\n\nGiven postfix expression: ");
display(postfix);
printf("\n");

return 0;
}
OUTPUT

11. Implement the evaluation of postfix notation using stacks.


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

// Experiment 11: Implement the evaluation of postfix notation using stacks.

struct stack {
int *stk;
int size;
int top;
};

bool isEmpty(struct stack *s) {


return (s->top == -1);
}

bool isFull(struct stack *s) {


return (s->top == s->size - 1);
}

void push(struct stack *s,int x) {


if (isFull(s)) {
return;
}

s->top++;
s->stk[s->top] = x;
}

char pop(struct stack *s) {


if (isEmpty(s)) {
return '?'; // ? is just a symbol to know that stack is empty
}

s->top--;
return s->stk[s->top+1];
}

char top(struct stack *s) {


if (isEmpty(s)) {
return '?'; // ? is just a symbol to know that stack is empty
}

return s->stk[s->top];
}

int isOperator(char x) {
if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^') return 1;
return 0;
}

int isNumber(char x) {
if (x >= 48 && x <= 57) return 1;
return 0;
}

int checkPostfixExpression(char *postfix) {


int noOfOperators=0,noOfOperands=0;
for (int i=0;postfix[i] != '\0';i++) {
if (isOperator(postfix[i])) {
if (i == 0) return 0; // If last or first char is operator
if (noOfOperands <= noOfOperators) return 0;
noOfOperators++;
} else if (isNumber(postfix[i]))
noOfOperands++;
else // Since we are supposed to evaluate the postfix expression , we
cannot accept anything other than numbers and operators
return 0;
}
if (noOfOperands != noOfOperators+1) return 0;
return 1;
}

int calculate(char * postfix) {


struct stack s;
s.stk = (int *)malloc(sizeof(int)*100);
s.size = 100;
s.top = -1;
for (int i=0;postfix[i] != '\0';i++) {
if (isNumber(postfix[i]))
push(&s,postfix[i]-'0');
else {
int a,b,result;
b = pop(&s);
a = pop(&s);
switch (postfix[i])
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '^':
result = a ^ b;
break;
default:
printf("Unexpected operator encountered");
return 0;
break;
}
push(&s,result);
}
}

if (s.top != 0) {
printf("Unexpected error occurred. More than one values in stack after
executing postfix expression");
return 0;
}
return pop(&s);
}

void display(char *x) {


for (int i=0;x[i] != '\0';i++) {
printf("%c",x[i]);
}
}

int main() {
char postfix[100],temp;
printf("Enter your postfix expression(enter '?' whenever to stop): ");

int i=0;
for (;i<99;i++) {
// printf("Input %d: ",i+1);
scanf(" %c",&temp);
if (temp == '?') break;
postfix[i] = temp;
}
if (i == 99) printf("You have reached max size of array");
postfix[i] = '\0';

int ch = checkPostfixExpression(postfix);
if (ch == 0) {
printf("Entered postfix expression is not valid\n");
return 0;
}

int result = calculate(postfix);

printf("\n\nGiven postfix expression: ");


display(postfix);
printf("\nResult: %d\n",result);

return 0;
}

OUTPUT

12. Implement binary search using recursion.


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

// Experiment 12: Implement binary search using recursion.

int binSearch(int A[],int l,int h,int x) {


if (l>h) return -1;

int mid = (l+h)/2;


if (A[mid] == x) return mid;
if (A[mid] < x) return binSearch(A,mid+1,h,x);
return binSearch(A,l,mid-1,x);
}

void display(int A[], int n) {


if (n == 0) {
printf("Array is empty\n");
return;
}

printf("Array is: ");


for (int i = 0; i < n; i++)
printf("%d ", A[i]);
printf("\n");
}

int main() {
int n;
printf("Enter size of array: ");
scanf("%d",&n);

if (n<=0) return 0;

int A[n];

printf("Enter elements of array in non-decreasing order\n");


int i=0;
while (i<n) {
printf("Input %d: ",i+1);
scanf("%d",&A[i]);
if (i>0 && A[i] < A[i-1]) {
printf("Invalid input, pls enter in non-decreasing format\n");
continue;
}
i++;
}

display(A,n);

int exit = 0;
while (exit == 0) {
int ch;
printf("\nMenu:\n1. Search an element\n2. Display\n3. Exit\nEnter a
choice:");
scanf("%d",&ch);
switch (ch) {
case 1:{
int x;
printf("Enter element to search: ");
scanf("%d",&x);
int index = binSearch(A,0,n-1,x);

display(A,n);
if (index == -1) printf("Element not found\n");
else printf("Element at index %d\n",index);

break;
}
case 2: {
display(A,n);
break;
}
case 3: {
exit = 1;
break;
}
default:{
printf("Invalid Choice\n");
break;
}
}
}

return 0;
}
OUTPUT

13. .Implement operations (enqueue, dequeue) on a queue using arrays.


Check the status of the queue whether it is empty or full.
#include <stdio.h>
#include <malloc.h>

// Experiment 13: Implement operations (enqueue, dequeue) on a queue using


arrays. Check the status of the queue whether it is empty or full.

struct queue {
int *Q;
int front;
int rear;
int size;
};

int isEmpty(struct queue *x) {


if (x->rear == x->front) {
// if (x->rear != -1) x->rear = x->front = -1; //For Optimization
return 1;
}
return 0;
}

int isFull(struct queue *x) {


if (x->rear == x->size-1) return 1;
return 0;
}

int enqueue(struct queue *x,int elem) {


if (isFull(x)) {
printf("Queue is Full\n");
return 0;
}

x->Q[++x->rear]=elem;
return 1;
}

int dequeue(struct queue *x) {


if (isEmpty(x)) {
printf("Queue is empty\n");
return -1;
}

return x->Q[++x->front];
}

void display(struct queue *x) {


if (isEmpty(x)) {
printf("Queue is empty\n");
return;
}

printf("Queue is: \nFront-> ");


for (int i=x->front+1;i<x->rear;i++)
printf("%d, ",x->Q[i]);
printf("%d <-Rear\n",x->Q[x->rear]);
}

int main() {
int temp;
printf("Enter max size of queue: ");
scanf("%d",&temp);
if (temp <=0) return 0;

struct queue q;
q.size = temp;
q.Q = (int *)malloc(sizeof(int)*temp);
q.front = q.rear = -1;

int exit=0;
while (exit == 0) {
int ch;
printf("\nMenu:\n1. Display\n2. Enqueue\n3. Dequeue\n4. Check Full\n5.
Check Empty\n6. Exit\nEnter your choice: ");
scanf("%d",&ch);

switch (ch) {
case 1: {
display(&q);
break;
}
case 2: {
int elem;
printf("Enter element to insert: ");
scanf("%d",&elem);
int status = enqueue(&q,elem);
display(&q);
break;
}
case 3: {
int elem = dequeue(&q);
if (elem != -1) {
printf("Element dequeued is %d\n",elem);
display(&q);
}
break;
}
case 4: {
printf(isFull(&q) ? "Queue is full\n": "Queue is not full\n");
break;
}
case 5: {
printf(isEmpty(&q) ? "Queue is empty\n": "Queue is not empty\
n");
break;
}
case 6: {
exit = 1;
break;
}
default:{
printf("Invalid choice\n");
break;
}
}
}

return 0;
}
OUTPUT

14. Implement circular queue using arrays and linked list.


#include <stdio.h>
#include <malloc.h>

// Experiment 14: Implement circular queue using arrays and linked list. (Part
1-Using Array)

struct queue {
int *Q;
int front;
int rear;
int size;
};

int isEmpty(struct queue *x) {


if (x->rear == x->front) return 1;
return 0;
}

int isFull(struct queue *x) {


if ((x->rear+1)%x->size == x->front) return 1;
return 0;
}

int enqueue(struct queue *x,int elem) {


if (isFull(x)) {
printf("Queue is Full\n");
return 0;
}

x->rear = (x->rear+1)%x->size;
x->Q[x->rear]=elem;
return 1;
}

int dequeue(struct queue *x) {


if (isEmpty(x)) {
printf("Queue is empty\n");
return -1;
}

x->front = (x->front+1)%x->size;
return x->Q[x->front];
}

void display(struct queue *x) {


if (isEmpty(x)) {
printf("Queue is empty\n");
return;
}

printf("Queue is: \nFront-> ");


for (int i=(x->front+1)%x->size;i!=x->rear;i=(i+1)%x->size)
printf("%d, ",x->Q[i]);
printf("%d <-Rear\n",x->Q[x->rear]);
}

int main() {
int temp;
printf("Enter max size of queue: ");
scanf("%d",&temp);
if (temp <=0) return 0;

struct queue q;
q.size = temp+1;
q.Q = (int *)malloc(sizeof(int)*temp+1);
q.front = q.rear = 0;

int exit=0;
while (exit == 0) {
int ch;
printf("\nMenu:\n1. Display\n2. Enqueue\n3. Dequeue\n4. Check Full\n5.
Check Empty\n6. Exit\nEnter your choice: ");
scanf("%d",&ch);
switch (ch) {
case 1: {
display(&q);
break;
}
case 2: {
int elem;
printf("Enter element to insert: ");
scanf("%d",&elem);
int status = enqueue(&q,elem);
display(&q);
break;
}
case 3: {
int elem = dequeue(&q);
if (elem != -1) {
printf("Element dequeued is %d\n",elem);
display(&q);
}
break;
}
case 4: {
printf(isFull(&q) ? "Queue is full\n": "Queue is not full\n");
break;
}
case 5: {
printf(isEmpty(&q) ? "Queue is empty\n": "Queue is not empty\
n");
break;
}
case 6: {
exit = 1;
break;
}
default:{
printf("Invalid choice\n");
break;
}
}
}

return 0;
}
OUTPUT
PART-2
#include <stdio.h>
#include <malloc.h>

// Experiment 14: Implement circular queue using arrays and linked list. (Part
2-Using Linked List)

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

struct queue {
struct node* front;
struct node* rear;
};

int isEmpty(struct queue *x) {


if (x->front == NULL) return 1;
return 0;
}

void enqueue(struct queue *x,int elem) {


struct node* q = (struct node *)malloc(sizeof(struct node));
q->val = elem;
q->next = NULL;

if (x->rear == NULL) {
// Queue was empty before
x->front = x->rear = q;
}
x->rear->next = q;
x->rear = q;
}

int dequeue(struct queue *x) {


if (isEmpty(x)) {
printf("Queue is empty\n");
return -1;
}
int elem = x->front->val;
if (x->front == x->rear) {
// Single element in queue
free(x->front);
x->front = x->rear = NULL;
return elem;
}

struct node * temp = x->front->next;


free(x->front);
x->front = temp;
return elem;
}

void display(struct queue *x) {


if (isEmpty(x)) {
printf("Queue is empty\n");
return;
}

struct node* p = x->front;


printf("Queue is: \nFront-> ");
while (p != x->rear) {
printf("%d, ",p->val);
p = p->next;
}
printf("%d <-Rear\n",x->rear->val);
}

int main() {
struct queue q;
q.front = q.rear = NULL;

int exit=0;
while (exit == 0) {
int ch;
printf("\nMenu:\n1. Display\n2. Enqueue\n3. Dequeue\n4. Check Empty\
n5. Exit\nEnter your choice: ");
scanf("%d",&ch);

switch (ch) {
case 1: {
display(&q);
break;
}
case 2: {
int elem;
printf("Enter element to insert: ");
scanf("%d",&elem);
enqueue(&q,elem);
display(&q);
break;
}
case 3: {
int elem = dequeue(&q);
if (elem != -1) {
printf("Element dequeued is %d\n",elem);
display(&q);
}
break;
}
case 4: {
printf(isEmpty(&q) ? "Queue is empty\n": "Queue is not empty\
n");
break;
}
case 5: {
exit = 1;
break;
}
default:{
printf("Invalid choice\n");
break;
}
}
}

return 0;
}

OUTPUT

15. Implement stacks and queues using linked list.


#include <stdio.h>
#include <malloc.h>

// Experiment 15: Implement stacks and queues using linked list.

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

// Functions and struct of stack

struct stack {
struct node* top;
};

int isEmptyStack(struct stack* stk) {


if (stk->top == NULL) return 1;
return 0;
}

void push(struct stack* stk,int elem) {


struct node* p = (struct node *)malloc(sizeof(struct node));
p->val = elem;
p->next = stk->top;
stk->top = p;
}

int pop(struct stack* stk) {


if (isEmptyStack(stk)) {
printf("Stack is empty\n");
return -1;
}

struct node* p = stk->top;


stk->top = stk->top->next;
int elem = p->val;
free(p);
return elem;
}

int peek(struct stack* stk) {


if (isEmptyStack(stk)) {
printf("Stack is empty\n");
return -1;
}

return stk->top->val;
}

void displayStack(struct stack* stk) {


if (isEmptyStack(stk)) {
printf("Stack is empty\n");
return ;
}
printf("\nStack is:\n%d <- Top\n",stk->top->val);
struct node* p = stk->top->next;
while (p != NULL) {
printf("%d\n",p->val);
p=p->next;
}
}

void stackMenu(struct stack* stk) {


int ch=1;
while (ch != 5) {
printf("\nMenu for Stack:\n1. Display\n2. Push\n3. Pop\n4. Peek\n5.
Exit\nEnter your choice: ");
scanf("%d",&ch);
switch (ch)
{
case 1:{
displayStack(stk);
break;
}
case 2: {
int elem;
printf("Enter element: ");
scanf("%d",&elem);
push(stk,elem);
displayStack(stk);
break;
}
case 3: {
int elem = pop(stk);
if (elem != -1) {
printf("Element popped is %d\n",elem);
displayStack(stk);
}
break;
}
case 4: {
int elem = peek(stk);
if (elem != -1) {
printf("Topmost element is %d\n",elem);
}
break;
}
case 5: {
printf("Exiting...\n");
break;
}
default:
printf("Invalid Choice");
break;
}
}
}

// Functions and struct of queue

struct queue {
struct node* front;
struct node* rear;
};

int isEmptyQueue(struct queue *x) {


if (x->front == NULL) return 1;
return 0;
}

void enqueue(struct queue *x,int elem) {


struct node* q = (struct node *)malloc(sizeof(struct node));
q->val = elem;
q->next = NULL;

if (x->rear == NULL) {
// Queue was empty before
x->front = x->rear = q;
}
x->rear->next = q;
x->rear = q;
}

int dequeue(struct queue *x) {


if (isEmptyQueue(x)) {
printf("Queue is empty\n");
return -1;
}

int elem = x->front->val;


if (x->front == x->rear) {
// Single element in queue
free(x->front);
x->front = x->rear = NULL;
return elem;
}

struct node * temp = x->front->next;


free(x->front);
x->front = temp;
return elem;
}

void displayQueue(struct queue *x) {


if (isEmptyQueue(x)) {
printf("Queue is empty\n");
return;
}

struct node* p = x->front;


printf("Queue is: \nFront-> ");
while (p != x->rear) {
printf("%d, ",p->val);
p = p->next;
}
printf("%d <-Rear\n",x->rear->val);
}

void queueMenu(struct queue *q) {


int ch=1;
while (ch != 5) {
printf("\nMenu for Queue:\n1. Display\n2. Enqueue\n3. Dequeue\n4.
Check Empty\n5. Exit\nEnter your choice: ");
scanf("%d",&ch);

switch (ch) {
case 1: {
displayQueue(q);
break;
}
case 2: {
int elem;
printf("Enter element to insert: ");
scanf("%d",&elem);
enqueue(q,elem);
displayQueue(q);
break;
}
case 3: {
int elem = dequeue(q);
if (elem != -1) {
printf("Element dequeued is %d\n",elem);
displayQueue(q);
}
break;
}
case 4: {
printf(isEmptyQueue(q) ? "Queue is empty\n": "Queue is not
empty\n");
break;
}
case 5: {
printf("Exiting...\n");
break;
}
default:{
printf("Invalid choice\n");
break;
}
}
}
}

int main() {
struct stack stk;
stk.top = NULL;

struct queue q;
q.front = q.rear = NULL;

int ch=1;
while (ch!=3) {
printf("\nMenu:\n1. Stack\n2. Queue\n3. Exit\nEnter your choice: ");
scanf("%d",&ch);

switch (ch) {
case 1:
stackMenu(&stk);
break;
case 2:
queueMenu(&q);
break;
case 3:
printf("Exiting...");
break;
default:
printf("Invalid Choice");
break;
}
}
}
OUTPUT
16.Implement Sparse Array.
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>

#define MAX_SIZE 100

struct SparseMatrix {
int *row_ind;
int *col_ind;
int *values;
int count;
};

void insert(struct SparseMatrix* mat, int i, int j, int val);


void display(struct SparseMatrix mat);
void deleteElement(struct SparseMatrix* mat, int i, int j);

struct SparseMatrix* create() {


struct SparseMatrix* mat = (struct SparseMatrix *)malloc(sizeof(struct
SparseMatrix));

mat->row_ind = (int *)malloc(sizeof(int)*MAX_SIZE);


mat->col_ind = (int *)malloc(sizeof(int)*MAX_SIZE);
mat->values = (int *)malloc(sizeof(int)*MAX_SIZE);

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


scanf("%d", &mat->row_ind[0]);
printf("Enter the number of columns: ");
scanf("%d", &mat->col_ind[0]);

if (mat->row_ind[0] <= 0 || mat->col_ind[0] <= 0) {


printf("\nInvalid size\n");
free(mat->row_ind);
free(mat->col_ind);
free(mat->values);
free(mat);
return NULL;
}
int value;
printf("Initializing matrix..\n");
for (int i=0;i<mat->row_ind[0];i++) {
for (int j = 0; j < mat->col_ind[0]; j++) {
printf("Enter value of row %d and column %d: ",i,j);
scanf("%d",&value);
if (value !=0) insert(mat,i,j,value);
}
}

display(*mat);

if (mat->values[0] >= mat->row_ind[0]*mat->col_ind[0]/2 + mat-


>row_ind[0]*mat->col_ind[0]%2) {
printf("\nThe above matrix has majority of non zero elements and is
not a sparse matrix\n");
free(mat->row_ind);
free(mat->col_ind);
free(mat->values);
free(mat);
return NULL;
}

return mat;
}

void insert(struct SparseMatrix* mat, int i, int j, int val) {


if (i < 0 || i >= mat->row_ind[0] || j < 0 || j >= mat->col_ind[0]) {
printf("Invalid indices\n");
return;
}

for (int k = 1; k <= mat->values[0]; k++) {


if (mat->row_ind[k] == i && mat->col_ind[k] == j) {
mat->values[k] = val;
if (val == 0) deleteElement(mat,i,j);
return;
}
}

if (val == 0) return;

if (mat->values[0] == 99) {
printf("Default max size reached\n");
return;
}

mat->values[0]++;
mat->row_ind[mat->values[0]] = i;
mat->col_ind[mat->values[0]] = j;
mat->values[mat->values[0]] = val;
}

void deleteElement(struct SparseMatrix* mat, int i, int j) {


if (i < 0 || i >= mat->row_ind[0] || j < 0 || j >= mat->col_ind[0]) {
printf("Invalid indices\n");
return;
}

if (mat->values[0] == 0) {
printf("Sparse matrix has no elements\n");
return;
}

for (int k = 1; k <= mat->values[0]; k++) {


if (mat->row_ind[k] == i && mat->col_ind[k] == j) {
int temp=mat->row_ind[k];
mat->row_ind[k] = mat->row_ind[mat->values[0]];
mat->row_ind[mat->values[0]] = temp;

temp=mat->col_ind[k];
mat->col_ind[k] = mat->col_ind[mat->values[0]];
mat->col_ind[mat->values[0]] = temp;

temp=0;
mat->values[k] = mat->values[mat->values[0]];
mat->values[mat->values[0]] = temp;

mat->values[0]--;
return;
}
}

printf("Element not found\n");


}

void display(struct SparseMatrix mat) {


printf("Sparse Array: \n");

printf("Row Col Value\n");


for (int k=0;k<=mat.values[0];k++) {
printf("%d %d %d\
n",mat.row_ind[k],mat.col_ind[k],mat.values[k]);
}

printf("There are %d non zero elements in matrix\n",mat.values[0]);


}

int main(){
struct SparseMatrix *mat = create();

if (mat == NULL) return 0;

int choice = 1;

while (choice != 4) {
printf("\nMenu:\n1. Insert an element\n2. Delete an element\n3.
Display the matrix\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1: {
int i, j, val;
printf("Enter the row index: ");
scanf("%d", &i);
printf("Enter the column index: ");
scanf("%d", &j);
printf("Enter the value: ");
scanf("%d", &val);
insert(mat, i, j, val);
display(*mat);
break;
}
case 2:{
int i, j;
printf("Enter the row index: ");
scanf("%d", &i);
printf("Enter the column index: ");
scanf("%d", &j);
deleteElement(mat, i, j);
display(*mat);
break;
}
case 3:
display(*mat);
break;
case 4:
break;
default:
printf("Invalid choice\n");
break; }
}
return 0;
}
OUTPUT

17. Implement operations on Binary Search Tree (Insertion, Deletion, Search,


Traversals (using recursion)- Inorder, Preorder, Postorder).
#include <stdio.h>
#include <malloc.h>

// Experiment 17: Implement operations on Binary Search Tree (Insertion,


Deletion, Search, Traversals (using recursion)- Inorder, Preorder, Postorder).

struct node {
int val;
struct node* left;
struct node* right;
};

struct node* insertBST(struct node* cur,int val) {


if (cur == NULL) {
struct node* p = (struct node*)malloc(sizeof(struct node));
p->val = val;
p->left = NULL;
p->right = NULL;
return p;
}

if (cur->val > val) cur->left = insertBST(cur->left,val);


if (cur->val <= val) cur->right = insertBST(cur->right,val);
return cur;
}

struct node* deleteBST(struct node* cur,int val) {


if (cur == NULL) return NULL;

if (cur->val == val) {
if (cur->left == NULL && cur->right == NULL) {
free(cur);
return NULL;
}

if (cur->left != NULL) {
struct node* leftLargest=cur->left;
while (leftLargest->right != NULL)
leftLargest = leftLargest->right;
cur->val = leftLargest->val;
cur->left = deleteBST(cur->left,leftLargest->val);
return cur;
}

struct node* rightSmallest=cur->right;


while (rightSmallest->left != NULL)
rightSmallest = rightSmallest->left;
cur->val = rightSmallest->val;
cur->right = deleteBST(cur->right,rightSmallest->val);
return cur;
}

if (cur->val > val) cur->left = deleteBST(cur->left,val);


if (cur->val < val) cur->right = deleteBST(cur->right,val);
return cur;
}

int searchBST(struct node* cur,int elem) {


if (cur == NULL) return 0;

if (cur->val > elem) return searchBST(cur->left,elem);


if (cur->val < elem) return searchBST(cur->right,elem);
return 1;
}

void preorder(struct node* cur) {


if (cur == NULL) return;

printf("%d ",cur->val);
preorder(cur->left);
preorder(cur->right);
}

void inorder(struct node* cur) {


if (cur == NULL) return;

inorder(cur->left);
printf("%d ",cur->val);
inorder(cur->right);
}

void postorder(struct node* cur) {


if (cur == NULL) return;

postorder(cur->left);
postorder(cur->right);
printf("%d ",cur->val);
}

int main() {
struct node* root = NULL;

int ch=1;
while (ch != 7) {
printf("\nMenu:\n1. Insert\n2. Delete\n3. Preorder\n4. Inorder\n5.
Postorder\n6. Search\n7. Exit\nEnter your choice: ");
scanf("%d",&ch);

switch (ch) {
case 1: {
int elem;
printf("Enter element to insert: ");
scanf("%d",&elem);
root = insertBST(root,elem);
break;
}
case 2: {
int elem;
printf("Enter element to delete: ");
scanf("%d",&elem);
root = deleteBST(root,elem);
break;
}
case 3:
printf("Preorder: ");
preorder(root);
printf("\n");
break;
case 4:
printf("Inorder: ");
inorder(root);
printf("\n");
break;
case 5:
printf("Postorder: ");
postorder(root);
printf("\n");
break;
case 6:{
int elem;
printf("Enter element to search: ");
scanf("%d",&elem);
int ch = searchBST(root,elem);
if (ch == 1) printf("Element found\n");
else printf("Element not found\n");
}
case 7:
break;
default:
printf("Invalid Choice");
break;
}
}

return 0;
}
OUTPUT

18. .Implement traversals on Binary Search Tree (using stacks) - Inorder,


Preorder, Postorder).
#include <stdio.h>
#include <malloc.h>

#define STACK_MAX_SIZE 100

// Experiment 18: Implement operations on Binary Search Tree (Insertion,


Deletion, Search, Traversals (using stacks)- Inorder, Preorder, Postorder).

struct node
{
int val;
struct node *left;
struct node *right;
};

struct nodeForSingleStack
{
struct node *val;
struct nodeForSingleStack *next;
};

// Functions and struct of stack

struct singleStack
{
struct nodeForSingleStack *top;
};

int isEmptySingleStack(struct singleStack *stk)


{
if (stk->top == NULL)
return 1;
return 0;
}

void pushSingleStack(struct singleStack *stk, struct node *elem)


{
struct nodeForSingleStack *p = (struct nodeForSingleStack
*)malloc(sizeof(struct nodeForSingleStack));
if (p == NULL)
return;
p->val = elem;
p->next = stk->top;
stk->top = p;
}

struct node *popSingleStack(struct singleStack *stk)


{
if (isEmptySingleStack(stk))
{
return NULL;
}

struct nodeForSingleStack *p = stk->top;


stk->top = stk->top->next;
struct node *elem = p->val;
free(p);
return elem;
}

struct nodeForDualStack
{
struct node *val;
int status;
struct nodeForDualStack *next;
};

// Functions and struct of stack

struct dualStack
{
struct nodeForDualStack *top;
};
int isEmptyDualStack(struct dualStack *stk)
{
if (stk->top == NULL)
return 1;
return 0;
}

void pushDualStack(struct dualStack *stk, struct node *elem, int status)


{
struct nodeForDualStack *p = (struct nodeForDualStack
*)malloc(sizeof(struct nodeForDualStack));
if (p == NULL)
return;
p->val = elem;
p->status = status;
p->next = stk->top;
stk->top = p;
}

struct nodeForDualStack *popDualStack(struct dualStack *stk)


{
if (isEmptyDualStack(stk))
return NULL;

struct nodeForDualStack *p = stk->top;


stk->top = stk->top->next;
return p;
}

struct node *insertBST(struct node *cur, int val)


{
if (cur == NULL)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = val;
p->left = NULL;
p->right = NULL;
return p;
}

if (cur->val > val)


cur->left = insertBST(cur->left, val);
if (cur->val <= val)
cur->right = insertBST(cur->right, val);
return cur;
}
struct node *deleteBST(struct node *cur, int val)
{
if (cur == NULL)
return NULL;

if (cur->val == val)
{
if (cur->left == NULL && cur->right == NULL)
{
free(cur);
return NULL;
}

if (cur->left != NULL)
{
struct node *leftLargest = cur->left;
while (leftLargest->right != NULL)
leftLargest = leftLargest->right;
cur->val = leftLargest->val;
cur->left = deleteBST(cur->left, leftLargest->val);
return cur;
}

struct node *rightSmallest = cur->right;


while (rightSmallest->left != NULL)
rightSmallest = rightSmallest->left;
cur->val = rightSmallest->val;
cur->right = deleteBST(cur->right, rightSmallest->val);
return cur;
}

if (cur->val > val)


cur->left = deleteBST(cur->left, val);
if (cur->val < val)
cur->right = deleteBST(cur->right, val);
return cur;
}

void preorder(struct node *root)


{
struct singleStack s;
s.top = NULL;

struct node *cur = root;


while (cur != NULL || !isEmptySingleStack(&s))
{
if (cur != NULL)
{
printf("%d ", cur->val);
pushSingleStack(&s, cur);
cur = cur->left;
continue;
}

cur = popSingleStack(&s);
cur = cur->right;
}
}

void inorder(struct node *root)


{
struct singleStack s;
s.top = NULL;

struct node *cur = root;


while (cur != NULL || !isEmptySingleStack(&s))
{
if (cur != NULL)
{
pushSingleStack(&s, cur);
cur = cur->left;
continue;
}

cur = popSingleStack(&s);
printf("%d ", cur->val);
cur = cur->right;
}
}

void postorder(struct node *root)


{
struct dualStack s;
s.top = NULL;

struct node *cur = root;


while (cur != NULL || !isEmptyDualStack(&s))
{
if (cur != NULL)
{
pushDualStack(&s, cur, 0);
cur = cur->left;
continue;
}

struct nodeForDualStack *r = popDualStack(&s);


cur = r->val;
if (r->status == 0)
{
pushDualStack(&s, cur, 1);
cur = cur->right;
}
else
{
printf("%d ", cur->val);
cur = NULL;
}
free(r);
}
}

int main()
{
struct node *root = NULL;

int ch = 1;
while (ch != 7)
{
printf("\nMenu:\n1. Insert\n2. Delete\n3. Preorder\n4. Inorder\n5.
Postorder\n6. Search\n7. Exit\nEnter your choice: ");
scanf("%d", &ch);

switch (ch)
{
case 1:
{
int elem;
printf("Enter element to insert: ");
scanf("%d", &elem);
root = insertBST(root, elem);
break;
}
case 2:
{
int elem;
printf("Enter element to delete: ");
scanf("%d", &elem);
root = deleteBST(root, elem);
break;
}
case 3:
printf("Preorder: ");
preorder(root);
printf("\n");
break;
case 4:
printf("Inorder: ");
inorder(root);
printf("\n");
break;
case 5:
printf("Postorder: ");
postorder(root);
printf("\n");
break;
case 6:
{
int elem;
printf("Enter element to search: ");
scanf("%d", &elem);
int ch = searchBST(root, elem);
if (ch == 1)
printf("Element found\n");
else
printf("Element not found\n");
}
case 7:
break;
default:
printf("Invalid Choice");
break;
}
}

return 0;
}
OUTPUT

19.Implement graph traversal (DFS & BFS)


#include <stdio.h>
#include <malloc.h>

// Experiment 19: Implement graph traversal (DFS & BFS) - (Undirected Graph)

#define MAX_VERTICES 100


#define QUEUE_SIZE 100

struct vertex
{
int adjacency[MAX_VERTICES];
int num_neighbors;
};

struct queue
{
int *Q;
int front;
int rear;
int size;
};

int isEmpty(struct queue *x)


{
if (x->rear == x->front)
return 1;
return 0;
}

int isFull(struct queue *x)


{
if ((x->rear + 1) % x->size == x->front)
return 1;
return 0;
}

int enqueue(struct queue *x, int elem)


{
if (isFull(x))
{
printf("Queue is Full\n");
return 0;
}

x->rear = (x->rear + 1) % x->size;


x->Q[x->rear] = elem;
return 1;
}

int dequeue(struct queue *x)


{
if (isEmpty(x))
{
printf("Queue is empty\n");
return -1;
}

x->front = (x->front + 1) % x->size;


return x->Q[x->front];
}

int visited[MAX_VERTICES];

void BFS(int start, struct vertex *graph, int num_vertices, int num_edges)
{
for (int i = 0; i < num_vertices; i++)
{
visited[i] = 0;
}

struct queue Q;
Q.front = Q.rear = -1;
Q.size = QUEUE_SIZE;
Q.Q = (int *)malloc(sizeof(int) * QUEUE_SIZE);
enqueue(&Q, start);
visited[start] = 1;

while (!isEmpty(&Q))
{
int u = dequeue(&Q);
printf("%d ", u);

for (int i = 0; i < graph[u].num_neighbors; i++)


{
int v = graph[u].adjacency[i];
if (!visited[v])
{
enqueue(&Q, v);
visited[v] = 1;
}
}
}
}

void DFS_helper(int u, struct vertex *graph)


{
visited[u] = 1;
printf("%d ", u);

int toVisit[MAX_VERTICES], n = 0;

for (int i = 0; i < graph[u].num_neighbors; i++)


{
int v = graph[u].adjacency[i];
if (visited[v] == 0)
{
visited[v] = 1;
toVisit[n++] = v;
}
}

for (int i = 0; i < n; i++)


{
int v = toVisit[i];
DFS_helper(v, graph);
}

visited[u] = 2;
}

void DFS(int start, struct vertex *graph, int num_vertices)


{
for (int i = 0; i < num_vertices; i++)
{
visited[i] = 0;
}

DFS_helper(start, graph);
}

void showAdjancencyLists(struct vertex *graph, int num_vertices)


{
printf("Adjacency lists:\n");
for (int i = 0; i < num_vertices; i++)
{
printf("Vertex %d: ", i);
for (int j = 0; j < graph[i].num_neighbors; j++)
{
printf("%d ", graph[i].adjacency[j]);
}
printf("\n");
}
}

int main()
{
int num_vertices, num_edges;
struct vertex *graph = (struct vertex *)malloc(sizeof(struct vertex) *
MAX_VERTICES);
printf("Enter the number of vertices: ");
scanf("%d", &num_vertices);
printf("Enter the number of edges: ");
scanf("%d", &num_edges);
//invalid case
if (num_vertices <= 0 || num_edges < 0)
return 0;

printf("\nThe edges are labeled 0 to %d\n", num_vertices - 1);

for (int i = 0; i < num_edges; i++)


{
int u, v;
printf("Enter an edge (u v): ");
scanf("%d %d", &u, &v);
if (u < 0 || u >= num_vertices || v < 0 || v >= num_vertices)
//checking the case
{
printf("Invalid edge\n");
i--; //decrementing the i
continue;
}

int already_present = 0;
for (int k = 0; k < graph[u].num_neighbors; k++)
{
if (graph[u].adjacency[k] == v)
{
already_present = 1;
break;
}
}

if (already_present)
{
printf("This vertices is already present!\n");
i--;
continue;
}

graph[u].adjacency[graph[u].num_neighbors++] = v;
graph[v].adjacency[graph[v].num_neighbors++] = u;
}

showAdjancencyLists(graph, num_vertices);

int choice = 1;
while (choice != 4)
{
printf("\nMenu:\n1. Breadth-first search\n2. Depth-first search\n3.
Show adjacency Lists\n4. Exit\nEnter your choice: ");

scanf("%d", &choice);

switch (choice)
{
case 1:
{
int start;
printf("Enter the starting vertex: ");
scanf("%d", &start);
BFS(start, graph, num_vertices, num_edges);
break;
}
case 2:
{
int start;
printf("Enter the starting vertex: ");
scanf("%d", &start);
DFS(start, graph, num_vertices);
break;
}
case 3:
showAdjancencyLists(graph, num_vertices);
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}

return 0;
}
OUTPUT
20. Make a menu driven program to perform various sorting techniques
(insertion, shell, merge, heap, bubble, quick).
#include <stdio.h>
#include <malloc.h>

// Experiment 20: Make a menu driven program to perform various sorting


techniques (insertion, shell, merge, heap, bubble, quick).

void insertionSort(int A[], int size);


void shellSort(int A[], int size);
void mergeSort(int A[], int size);
void heapSort(int A[], int size);
void bubbleSort(int A[], int size);
void quickSort(int A[], int size);

void swapAdd(int *a, int *b)


{
int temp = *a;
*a = *b;
*b = temp;
}

void display(int A[], int size)


{

if (size == 0)
{

printf("Array is empty\n");

return;
}

printf("Array is: ");

for (int i = 0; i < size; i++)


printf("%d ", A[i]);

printf("\nSize of array: %d\n", size);


}

// Insertion Sort

void insertionSort(int A[], int size)


{
for (int i = 1; i < size; i++)
{
int j = i - 1, x = A[i];
while (j >= 0 && A[j] > x)
{
A[j + 1] = A[j];
j--;
}
A[j + 1] = x;
}
}

// Shell Sort

void shellSort(int A[], int size)


{
int gap, i, j, temp;
for (gap = size / 2; gap >= 1; gap /= 2)
{
for (i = gap; i < size; i++)
{
temp = A[i];
j = i - gap;
while (j >= 0 && A[j] > temp)
{

A[j + gap] = A[j];

j -= gap;
}
A[j + gap] = temp;
}
}
}

// Merge Sort

void merge(int A[], int l, int mid, int h)


{

int B[100];

int i = l, j = mid + 1, k = 0;

while (i <= mid && j <= h)


{

if (A[i] < A[j])


B[k++] = A[i++];

else
B[k++] = A[j++];
}

for (; i <= mid; i++)


B[k++] = A[i++];

for (; j <= h; j++)


B[k++] = A[j++];

for (i = l, k = 0; i <= h; i++, k++)


A[i] = B[k];
}
void rMergeSort(int A[], int l, int h)
{
if (l < h)
{
int mid = (l + h) / 2;
rMergeSort(A, l, mid);
rMergeSort(A, mid + 1, h);
merge(A, l, mid, h);
}
}
void mergeSort(int A[], int size)
{
rMergeSort(A, 0, size - 1);
}

// Heap Sort
int heapSize = 0;
void insertHeap(int heap[], int key)
{
heap[heapSize] = key;
heapSize++;
if (heapSize > 1)
{
int i = heapSize - 1;
while (i > 0 && key > heap[(i - 1) / 2])
{
heap[i] = heap[(i - 1) / 2];
i = (i - 1) / 2;
}
heap[i] = key;
}
}
void deleteHeap(int heap[])
{
int x = heap[0];
heap[0] = heap[heapSize - 1];
heapSize--;
int i = 0, j = 2 * i + 1;
while (j < heapSize)
{
if (heap[j + 1] > heap[j])
j++;
if (heap[i] < heap[j])
{
swapAdd(&heap[i], &heap[j]);
i = j;
j = 2 * i + 1;
}
else
break;
}
heap[heapSize] = x;
}
void heapSort(int A[], int size)
{
for (int i = 0; i < size; i++)
insertHeap(A, A[i]);
for (int i = 1; i < size; i++)
deleteHeap(A);
}
// Bubble Sort
void bubbleSort(int A[], int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - 1 - i; j++)
{
if (A[j] > A[j + 1])
{
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}
// Quick Sort
int Partition(int A[], int l, int h)
{
int Pivot = A[l];
int i = l, j = h;
do
{
do
{
i++;
} while (A[i] <= Pivot);
do
{
j--;
} while (A[j] > Pivot);
if (i < j)
swapAdd(&A[i], &A[j]);
} while (i < j);
swapAdd(&A[l], &A[j]);
return j;
}
void rQuickSort(int A[], int l, int h)
{
int j;
if (l < h)
{
j = Partition(A, l, h);
rQuickSort(A, l, j);
rQuickSort(A, j + 1, h);
}
}
void quickSort(int A[], int size)
{
A[size] = 32456;
rQuickSort(A, 0, size);
}
int main()
{
int size;
printf("Enter size of array: ");
scanf("%d", &size);
int A[size + 1];
for (int i = 0; i < size; i++)
{
printf("Enter %dth element: ", i + 1);
scanf("%d", &A[i]);
}
int ch;
printf("1. Insertion\n2. shell\n3. merge\n4. heap\n5. bubble\n6. quick\n7.
Exit\nEnter your choice");
scanf("%d", &ch);
switch (ch) {
case 1:
insertionSort(A, size);
break;
case 2:
shellSort(A, size);
break;
case 3:
mergeSort(A, size);
break;
case 4:
heapSort(A, size);
break;
case 5:
bubbleSort(A, size);
break;
case 6:
quickSort(A, size);
break;
case 7:
break;
default:
break;
}
display(A, size);
return 0;
}
OUTPUT

You might also like