DS Lab Manual R23 Final
DS Lab Manual R23 Final
ii. C Programs to implement the Searching Techniques – Linear & Binary Search
Linear Search
#include<stdio.h>
int main() {
// declaration of the array and other variables
int arr[20], size, key, i, index;
int countKey = 0; //initializing count of key element as 0
printf("...enter size of array.... ");
scanf("%d", &size);
printf(".....Enter elements of the array..... ");
// loop for the input of elements from 0 to number of elements-1
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("....elements of array..... \n");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n.....Enter the element to search.....\n");
scanf("%d", &key);
// loop for traversing the array from 0 to the number of elements-1
for (index = 0; index < size; index++) {
if (arr[index] == key) { // comparing each element with the key element
printf("Key element found at index %d\n", index); // printing the index if key found
countKey++; // incrementing the count of key element;
}
}
if (countKey == 0) // condition to check whether key element is found or not
printf("Key element not found");
else
printf("Key element is present %d times in the array.\n", countKey);
return 0;
}
Output:
...enter size of array.... 5
.....Enter elements of the array..... 2
4
2
8
2
....elements of array.....
24282
.....Enter the element to search.....
2
Key element found at index 0
Key element found at index 2
Key element found at index 4
Key element is present 3 times in the array.
Information Technology
Binary Search
#include <stdio.h>
int binarySearch(int array[], int x, int low, int high) {
// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int arr[100], size, key, i, index;
printf("...enter size of array.... ");
scanf("%d", &size);
printf(".....Enter elements of the array..... ");
// loop for the input of elements from 0 to number of elements-1
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("....elements of array..... \n");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n.....Enter the element to search.....\n");
scanf("%d", &key);
int result = binarySearch(arr, key, 0, size);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}
Output:
...enter size of array.... 5
.....Enter elements of the array..... 2
4
8
1
6
....elements of array.....
24816
.....Enter the element to search.....
8
Element is found at index 2
Information Technology
iii. C Programs to implement Sorting Techniques – Bubble, Selection and Insertion Sort
Bubble sort
// C program for implementation of Bubble sort
#include <stdio.h>
int main(){
int arr[50], num, x, y, temp;
printf("Enter size of the array: ");
scanf("%d", &num);
printf("......Enter array Elements......");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
printf("......array Elements are......\n");
for(x = 0; x < num; x++)
printf("%d ", arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("\n.....Array after bubble sort bubble sort......\n");
for(x = 0; x < num; x++){
printf("%d ", arr[x]);
}
return 0;
}
Output:
Enter size of the array: 5
......Enter array Elements......3
1
7
5
0
......array Elements are......
3 1 7 5 0
.....Array after bubble sort bubble sort......
0 1 3 5 7
Information Technology
Selection sort
// C program for implementation of Selection sort
#include <stdio.h>
int main()
{
int array[100], n, c, d, position, t;
printf(".....Enter number of elements....\n");
scanf("%d", &n);
printf("....Enter %d integers....\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("....Array elements are....\n");
for (c = 0; c < n; c++)
printf("%d ", array[c]);
for (c = 0; c < (n - 1); c++) // finding minimum element (n-1) times
{
position = c;
for (d = c + 1; d < n; d++)
{
if (array[position] > array[d])
position = d;
}
if (position != c)
{
t = array[c];
array[c] = array[position];
array[position] = t;
}
}
printf("\n....Sorted list in ascending order.....\n");
for (c = 0; c < n; c++)
printf("%d ", array[c]);
return 0;
}
Output:
.....Enter number of elements....
5
....Enter 5 integers....
4
2
9
3
6
....Array elements are .....
4 2 9 3 6
....Sorted list in ascending order.....
2 3 4 6 9
Information Technology
Insertion sort
// C program for implementation of insertion sort
#include <stdio.h>
int main(void)
{
int n, i, j, temp;
int arr[64];
printf("....Enter number of elements.....\n");
scanf("%d", &n);
printf(".....Enter %d integers....\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("\n....array elements are.....\n");
for (i = 0; i < n; i++)
{ printf("%d ", arr[i]); }
for (i = 1; i < n; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("\n.....Sorted list in ascending order.....\n");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
....Enter number of elements.....
5
.....Enter 5 integers....
7
9
3
6
11
....array elements are.....
7 9 3 6 11
.....Sorted list in ascending order.....
3 6 7 9 11
Information Technology
return;
}
struct Node* temp = *head;
struct Node* prev = NULL;
if (position == 1) {
*head = temp->next;
free(temp);
return;
}
for (int i = 1; temp != NULL && i < position; i++) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf(".....Invalid position.....\n");
return;
}
prev->next = temp->next;
free(temp);
}
void displayList(struct Node* head) {
struct Node* temp = head;
// Traverse and print the list
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// Insert elements at the beginning
insertAtBeginning(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtBeginning(&head, 4);
insertAtBeginning(&head, 5);
// Display the original list
printf("........Linked List....... ");
displayList(head);
// Delete node at the beginning
deleteAtBeginning(&head);
// Display the list after deletion at the beginning
printf(".....Linked List after deletion at the beginning.... ");
displayList(head);
// Delete node at the end
deleteAtEnd(&head);
// Display the list after deletion at the end
Information Technology
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
printf(".....Given linked list is ......\n");
printList(head);
reverse(&head);
printf("\n.......Reversed linked list is........ \n");
printList(head);
getchar();
}
Output:
.....Given linked list is ......
85 15 4 20
.......Reversed linked list is........
20 4 15 85
{
if (head == NULL)
{
return;
}
//Recursive call first
print_reverse_recursive (head -> next);
//Print later
printf ("%d ", head -> data);
}
//Print the linkedlist normal
void print (struct node *head)
{
if (head == NULL)
{
return;
}
printf ("%d ", head -> data);
print (head -> next);
}
//New data added in the start
void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}
Output:
......LinkedList.....4 3 2 1
....LinkedList in reverse order....1 2 3 4
Information Technology
struct node {
int data;
struct node *next;
};
temp->next = newNode;
head = head->next;
temp->next = temp->next->next;
// Search a node
bool searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;
free(q);
q = p->next;
}
}
}
int main()
{
int A[] = { 33, 33, 8, 8, 8 };
create (A, 5);
printf ("......Linked List with Duplicates..... \n");
display (first);
removeDuplicate (first);
printf ("\n......Linked List without Duplicates....... \n");
display (first);
return 0;
}
Output:
......Linked List with Duplicates.....
33 33 8 8 8
......Linked List without Duplicates.......
33
Information Technology
poly1 = poly1->next;
} else {
insert(&result, poly2->coef, poly2->exp);
poly2 = poly2->next;
}
}
while (poly1 != NULL) {
insert(&result, poly1->coef, poly1->exp);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insert(&result, poly2->coef, poly2->exp);
poly2 = poly2->next;
}
return result;
}
int main() {
Node* poly1 = NULL;
insert(&poly1, 5, 4);
insert(&poly1, 3, 2);
insert(&poly1, 1, 0);
Node* poly2 = NULL;
insert(&poly2, 4, 4);
insert(&poly2, 2, 2);
insert(&poly2, 1, 1);
printf("First polynomial: ");
print(poly1);
printf("Second polynomial: ");
print(poly2);
Node* result = add(poly1, poly2);
printf("Result: ");
print(result);
return 0;
}
Output:
First polynomial: 5x^4 + 3x^2 + 1x^0
Second polynomial: 4x^4 + 2x^2 + 1x^1
Result: 9x^4 + 5x^2 + 1x^1 + 1x^0
Information Technology
deque[r]=x;
}
}
// display function prints all the value of deque.
void display()
{
int i=f;
printf("\nElements in a deque are: ");
while(i!=r)
{
printf("%d ",deque[i]);
i=(i+1)%size;
}
printf("%d",deque[r]);
}
// getfront function retrieves the first value of the deque.
void getfront()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at front is: %d", deque[f]);
}
}
// getrear function retrieves the last value of the deque.
void getrear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at rear is: %d", deque[r]);
}
}
// delete_front() function deletes the element from the front
void delete_front()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
Information Technology
}
else if(f==r)
{
printf("\nThe deleted element at front is:%d", deque[f]);
f=-1;
r=-1;
}
else if(f==(size-1))
{
printf("\nThe deleted element at front is:%d", deque[f]);
f=0;
}
else
{
printf("\nThe deleted element at front is:%d", deque[f]);
f=f+1;
}
}
// delete_rear() function deletes the element from the rear
void delete_rear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element at rear is: %d", deque[r]);
f=-1;
r=-1;
}
else if(r==0)
{
printf("\nThe deleted element at rear is: %d", deque[r]);
r=size-1;
}
else
{
printf("\nThe deleted element at rear is: %d", deque[r]);
r=r-1;
}
}
int main()
{
insert_front(200);
insert_front(100);
insert_rear(300);
insert_rear(500);
Information Technology
insert_rear(800);
display(); // Calling the display function to retrieve the values of deque
getfront(); // Retrieve the value at front-end
getrear(); // Retrieve the value at rear-end
delete_front();
delete_rear();
display(); // calling display function to retrieve values after deletion
return 0;
}
Output:
Elements in a deque are: 100 200 300 500 800
The value of the element at front is: 100
The value of the element at rear is: 800
The deleted element at front is:100
The deleted element at rear is: 800
Elements in a deque are: 200 300 500
Information Technology
(Note: you can ignore writing comments in observation or record; those are
mentioned just for u r understanding purpose of code)
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void insertAtFront(struct Node** head, int data) {
// Create a new struct node and allocate memory.
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// Initialize data in the newly created node.
newNode->data = data;
// Make the next pointer of the new node point to the head.
// In this way, this new node is added at front of the linked list.
newNode->next = (*head);
newNode->prev = NULL;
// If the head is not NULL, then we update the prev pointer in the current head.
// The prev pointer of the current head will point to the new node.
if((*head) != NULL) {
(*head)->prev = newNode;
}
// Update the head pointer to point to the new node.
(*head) = newNode;
}
void insertAtEnd(struct Node** head, int data) {
// Create a new struct node and allocate memory.
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// Initialize data in the newly created node.
newNode->data = data;
newNode->next = NULL;
if((*head) == NULL) {
// If the head is NULL, then the new node is the new head.
newNode->prev = NULL;
// Assign head as the new node.
(*head) = newNode;
return ;
}
// If the list is not empty then traverse to the end of the list.
struct Node* ptr = (*head);
while(ptr->next != NULL) {
ptr = ptr->next;
Information Technology
}
// From the last node, add a link to the new node.
ptr->next = newNode;
// Update the prev pointer in the new node to point to the previous last node.
newNode->prev = ptr;
}
void insertAfterNode(struct Node* node, int data) {
if(node == NULL) {
// If the node is NULL, then we cannot insert.
printf("The given node cannot be NULL.");
return ;
}
// Create a new struct node and allocate memory.
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// Initialize data in the newly created node.
newNode->data = data;
// Add a link from new node to next_node.
newNode->next = node->next;
// Add a link from the given node to the new node.
node->next = newNode;
// Update the prev pointer of the new node to the given node.
newNode->prev = node;
// If the next_node is not NULL, then update the prev of the next_node.
if(newNode->next != NULL) {
newNode->next->prev = newNode;
}
}
void insertBeforeNode(struct Node** head, struct Node* node, int data) {
if(node == NULL) {
// If the given node is NULL, then we cannot insert a node before a NULL node.
printf("The given node cannot be NULL.");
return ;
}
// Create a new struct node and allocate memory.
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// Initialize data in the newly created node.
newNode->data = data;
// Add a link from the new node to the given node.
newNode->next = node;
if(node->prev != NULL) {
// If the given node is not the head node, then we update the next pointer of previous node
node->prev->next = newNode;
// Update the prev pointer of the new node to point to the previous node.
newNode->prev = node->prev;
}
else {
// If the previous value is NULL, then this means the given node is head.
// So we are inserting it at the front of head.
Information Technology
// Hence, we update the value of the head pointer to the new node.
*head = newNode;
}
// Update the previous pointer of the given node.
node->prev = newNode;
}
void deleteAtFront(struct Node** head) {
// If the head pointer is NULL, then we cannot delete it.
if((*head) == NULL) return ;
struct Node* curr = *head;
// Update the head pointer to the next node.
*head = (*head)->next;
// Make the previous head pointer NULL and free the memory.
curr->next = NULL;
free(curr);
}
void deleteAtLast(struct Node** head) {
// If the head pointer is NULL, then we cannot delete it.
if((*head) == NULL) return ;
// Traverse to the last node.
struct Node* curr = *head;
while(curr->next != NULL) {
curr = curr->next;
}
// Second last node will point to NULL.
struct Node* prev = curr->prev;
prev->next = NULL;
// Make the last node NULL and free the memory.
curr->prev = NULL;
free(curr);
}
void deleteAtPosition(struct Node** head, int position) {
struct Node* curr = *head;
if(position == 1) {
// If the position is 1, then delete the head and return.
deleteAtFront(head);
return ;
}
// Go the node to be deleted.
while(position > 1 && curr) {
// While the position is greater than 1 and the current node is not NULL,
// we iterate forward and decrease position by 1.
curr = curr->next;
position --;
}
// If the current node is NULL, then we cannot delete it.
// The node at the specified position does not exist.
if(curr == NULL) {
Information Technology
traverse(head);
printf("Delete the last node\n");
deleteAtLast(&head);
traverse(head);
printf("Delete the second node from the front.\n");
deleteAtPosition(&head, 2);
traverse(head);
return 0;
}
Output:
Insert 1 at the front
1 -> NULL
Insert 2 at the front
2 <--> 1 -> NULL
Insert 4 at the end
2 <--> 1 <--> 4 -> NULL
Insert 5 at the front
2 <--> 1 <--> 4 <--> 5 -> NULL
Insert 3 after head->next
2 <--> 1 <--> 3 <--> 4 <--> 5 -> NULL
Insert -1 before the head
-1 <--> 2 <--> 1 <--> 3 <--> 4 <--> 5 -> NULL
Insert 100 before head->next->next
-1 <--> 2 <--> 100 <--> 1 <--> 3 <--> 4 <--> 5 -> NULL
Delete the front node.
2 <--> 100 <--> 1 <--> 3 <--> 4 <--> 5 -> NULL
Delete the last node
2 <--> 100 <--> 1 <--> 3 <--> 4 -> NULL
Delete the second node from the front.
1 <--> 1 <--> 3 <--> 4 -> NULL
Information Technology
ii) Implement a circular linked list and perform insertion, deletion, and traversal.
(Note: you can ignore writing comments in observation or record; those are
mentioned just for u r understanding purpose of code)
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* addToEmpty(struct Node* last, int data) {
if (last != NULL) return last;
// allocate memory to the new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// assign data to the new node
newNode->data = data;
// assign last to newNode
last = newNode;
// create link to iteself
last->next = last;
return last;
}
// add node to the front
struct Node* addFront(struct Node* last, int data) {
// check if the list is empty
if (last == NULL) return addToEmpty(last, data);
// allocate memory to the new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// add data to the node
newNode->data = data;
// store the address of the current first node in the newNode
newNode->next = last->next;
// make newNode as head
last->next = newNode;
return last;
}
// add node to the end
struct Node* addEnd(struct Node* last, int data) {
// check if the node is empty
if (last == NULL) return addToEmpty(last, data);
// allocate memory to the new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
// add data to the node
newNode->data = data;
// store the address of the head node to next of newNode
newNode->next = last->next;
// point the current last node to the newNode
last->next = newNode;
Information Technology
*last = temp->next;
}
// travel to the node to be deleted
while (temp->next != *last && temp->next->data != key) {
temp = temp->next;
}
// if node to be deleted was found
if (temp->next->data == key) {
d = temp->next;
temp->next = d->next;
free(d);
}
}
void traverse(struct Node* last) {
struct Node* p;
if (last == NULL) {
printf("The list is empty");
return;
}
p = last->next;
do {
printf("%d ", p->data);
p = p->next;
} while (p != last->next);
}
int main() {
struct Node* last = NULL;
last = addToEmpty(last, 6);
last = addEnd(last, 8);
last = addFront(last, 2);
last = addAfter(last, 10, 2);
traverse(last);
deleteNode(&last, 8);
printf("\n");
traverse(last);
return 0;
}
Output:
2 10 6 8
10 6 2
Information Technology
int is_empty() {
if(top == 0)
return 1;
return 0;
}
void push(int x) {
top = top+1;
if(top > SIZE) {
printf("Stack Overflow\n");
}
else {
S[top] = x;
}
}
int pop() {
if(is_empty()) {
printf("Stack Underflow\n");
return -1000;
}
else {
top = top-1;
return S[top+1];
}
}
int main() {
pop();
push(10);
push(20);
push(30);
push(40);
push(50);
push(60);
push(70);
push(80);
push(90);
push(100);
push(110);
int i;
Information Technology
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n");
}
int is_empty(stack *s) {
if(s->top == NULL)
return 1;
return 0;
}
void push(stack *s, node *n) {
if(is_empty(s)) { //empty
s->head = n;
s->top = n;
}
else {
s->top->next = n;
s->top = n;
}
}
//function to delete
int pop(stack *s) {
if(is_empty(s)) {
printf("Stack Underflow\n");
return -1000;
}
else {
int x = s->top->data;
if(s->top == s->head) {// only one node
free(s->top);
s->top = NULL;
s->head = NULL;
}
else {
node *temp = s->head;
while(temp->next != s->top) // iterating to the last element
temp = temp->next;
temp->next = NULL;
free(s->top);
s->top = temp;
}
return x;
}
}
int main() {
stack *s = new_stack();
node *a, *b, *c;
a = new_node(10);
Information Technology
b = new_node(20);
c = new_node(30);
pop(s);
push(s, a);
push(s, b);
push(s, c);
traversal(s);
pop(s);
traversal(s);
return 0;
}
Output:
Stack Underflow
10 20 30
10 20
Information Technology
return stack;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1 ;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}
int evaluatePostfix(char* exp)
{
struct Stack* stack = createStack(strlen(exp));
int i;
if (!stack) return -1;
for (i = 0; exp[i]; ++i)
{
if (isdigit(exp[i]))
Information Technology
{
printf("OVERFLOW\n");
return;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear+1;
}
queue[rear] = item;
printf("....Value inserted....\n");
}
void delete()
{
int item;
if (front == -1 || front > rear)
{
printf("UNDERFLOW\n");
return;
}
else
{
item = queue[front];
if(front == rear)
{
front = -1;
rear = -1 ;
}
else
{
front = front + 1;
}
printf("....value deleted....\n");
}
}
void display()
{
int i;
if(rear == -1)
{
printf("...Empty queue\n");
}
else
{ printf("....printing values .....\n");
Information Technology
for(i=front;i<=rear;i++)
{
printf("\n%d\n",queue[i]);
}
}
}
Output:
……Main Menu……
-----------------------------
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
……Enter your choice ….1
….Enter the element……
123
….Value inserted….
……Main Menu……
-----------------------------
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
……Enter your choice …..1
….Enter the element…..
90
….Value inserted…..
……Main Menu……
-----------------------------
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
….Enter your choice……2
….Value deleted….
….Enter your choice……3
....printing values .....
123
90
Information Technology
{
printf("\nOVERFLOW\n");
return;
}
else
{
printf(".....Enter value.....\n");
scanf("%d",&item);
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;
}
}
}
void delete ()
{
struct node *ptr;
if(front == NULL)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
ptr = front;
front = front -> next;
free(ptr);
}
}
void display()
{
struct node *ptr;
ptr = front;
if(front == NULL)
{
printf("\nEmpty queue\n");
}
else
Information Technology
……Main Menu……
-----------------------------
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
….Enter your choice……2
….Value deleted….
….Enter your choice……3
....printing values .....
123
90
Information Technology
free(temp);
if (queue->front == NULL) {
queue->rear = NULL;
}
}
// Function to display the contents of the printer queue
void displayQueue(PrinterQueue *queue) {
if (isEmpty(queue)) {
printf("Printer Queue is empty\n");
return;
}
Job *currentJob = queue->front;
printf("Printer Queue: ");
while (currentJob != NULL) {
printf("%d ", currentJob->jobNumber);
currentJob = currentJob->nextJob;
}
printf("\n");
}
int main() {
PrinterQueue printerQueue;
initQueue(&printerQueue);
// Enqueue some jobs
enqueue(&printerQueue, 1);
enqueue(&printerQueue, 2);
enqueue(&printerQueue, 3);
// Display the queue
displayQueue(&printerQueue);
// Dequeue a job
dequeue(&printerQueue);
// Display the updated queue
displayQueue(&printerQueue);
return 0;
}
Output:
Printer Queue: 1 2 3
Printer Queue: 2 3
Information Technology
queue->front = -1;
queue->rear = -1;
} else {
queue->front = (queue->front + 1) % MAX_SIZE;
}
return value;
}
// Function to display the elements in the circular queue
void displayQueue(CircularQueue *queue) {
if (isEmpty(queue)) {
printf("Circular Queue is empty\n");
return;
}
printf("Circular Queue: ");
int i = queue->front;
do {
printf("%d ", queue->items[i]);
i = (i + 1) % MAX_SIZE;
} while (i != (queue->rear + 1) % MAX_SIZE);
printf("\n");
}
int main() {
CircularQueue circularQueue;
initCircularQueue(&circularQueue);
// Enqueue elements into the circular queue
enqueue(&circularQueue, 1);
enqueue(&circularQueue, 2);
enqueue(&circularQueue, 3);
enqueue(&circularQueue, 4);
enqueue(&circularQueue, 5);
displayQueue(&circularQueue);
// Dequeue elements from the circular queue
printf("Dequeued: %d\n", dequeue(&circularQueue));
printf("Dequeued: %d\n", dequeue(&circularQueue));
displayQueue(&circularQueue);
// Enqueue another element after dequeue
enqueue(&circularQueue, 6);
displayQueue(&circularQueue);
return 0;
}
Output:
Enqueued: 6
Circular Queue: 3 4 5 6
Information Technology
return 3;
}
return -1;
}
int covertInfixToPostfix(char* expression)
{
int i, j;
for (i = 0, j = -1; expression[i]; ++i)
{
if (checkIfOperand(expression[i]))
expression[++j] = expression[i];
else if (expression[i] == '(')
push(expression[i]);
else if (expression[i] == ')')
{
while (!isEmpty() && peek() != '(')
expression[++j] = pop();
if (!isEmpty() && peek() != '(')
return -1; // invalid expression
else
pop();
}
else // if an opertor
{
while (!isEmpty() && precedence(expression[i]) <= precedence(peek()))
expression[++j] = pop();
push(expression[i]);
}
}
while (!isEmpty())
expression[++j] = pop();
expression[++j] = '\0';
printf( "%s", expression);
}
int main()
{
char expression[] = "((p+(q*r))-s)";
covertInfixToPostfix(expression);
return 0;
}
Output:
pqr*+s-
Information Technology
iii) Implement a stack or queue to perform comparison and check for symmetry.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
// Structure to represent a stack node
typedef struct StackNode {
char data;
struct StackNode *next;
} StackNode;
// Structure to represent a stack
typedef struct {
StackNode *top;
} Stack;
// Function to initialize the stack
void initStack(Stack *stack) {
stack->top = NULL;
}
// Function to check if the stack is empty
bool isEmpty(Stack *stack) {
return (stack->top == NULL);
}
// Function to push an element onto the stack
void push(Stack *stack, char data) {
StackNode *newNode = (StackNode *)malloc(sizeof(StackNode));
if (newNode == NULL) {
fprintf(stderr, "Error: Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}
// Function to pop an element from the stack
char pop(Stack *stack) {
if (isEmpty(stack)) {
fprintf(stderr, "Error: Stack is empty\n");
exit(1);
}
StackNode *temp = stack->top;
char poppedData = temp->data;
stack->top = temp->next;
free(temp);
return poppedData;
}
// Function to perform symmetry check on a string
bool isSymmetric(char *str) {
Stack stack;
Information Technology
initStack(&stack);
// Push alphanumeric characters onto the stack
for (int i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i])) {
push(&stack, tolower(str[i]));
}
}
// Compare characters from the stack with the remaining characters in the string
for (int i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i])) {
char stackChar = pop(&stack);
if (tolower(str[i]) != stackChar) {
return false; // Not symmetric
}
}
}
return isEmpty(&stack); // Stack should be empty if symmetric
}
int main() {
char inputString[100];
printf("Enter a string to check for symmetry: ");
fgets(inputString, sizeof(inputString), stdin);
// Remove newline character from input
inputString[strcspn(inputString, "\n")] = '\0';
if (isSymmetric(inputString)) {
printf("The string is symmetric.\n");
} else {
printf("The string is not symmetric.\n");
}
return 0;
}
Output:
Enter a string to check for symmetry: gghgg
The string is symmetric.
Information Technology
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the BST
typedef struct TreeNode {
int key;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// Function to create a new node with the given key
TreeNode* createNode(int key) {
TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
if (newNode == NULL) {
fprintf(stderr, "Error: Memory allocation failed\n");
exit(1);
}
newNode->key = key;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert a key into the BST
TreeNode* insert(TreeNode* root, int key) {
if (root == NULL) {
return createNode(key);
}
if (key < root->key) {
root->left = insert(root->left, key);
} else if (key > root->key) {
root->right = insert(root->right, key);
}
return root;
}
// Inorder Traversal: Visit left subtree, current node, then right subtree
void inorderTraversal(TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->key);
inorderTraversal(root->right);
}
}
// Preorder Traversal: Visit current node, left subtree, then right subtree
void preorderTraversal(TreeNode* root) {
if (root != NULL) {
printf("%d ", root->key);
preorderTraversal(root->left);
preorderTraversal(root->right);
Information Technology
}
}
// Postorder Traversal: Visit left subtree, right subtree, then current node
void postorderTraversal(TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->key);
}
}
int main() {
TreeNode* root = NULL;
// Insert keys into the BST
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// Perform inorder traversal (ascending order)
printf("Inorder traversal (ascending order): ");
inorderTraversal(root);
printf("\n");
// Perform preorder traversal
printf("Preorder traversal: ");
preorderTraversal(root);
printf("\n");
// Perform postorder traversal
printf("Postorder traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}
Output:
Inorder traversal (ascending order): 20 30 40 50 60 70 80
Preorder traversal: 50 30 20 40 70 60 80
Postorder traversal: 20 40 30 60 80 70 50
Information Technology
Exercise 9: Hashing
i) Implement a hash table with collision resolution techniques.
Chaining
#include<stdio.h>
#include<stdlib.h>
#define size 7
struct node
{
int data;
struct node *next;
};
struct node *chain[size];
void init()
{
int i;
for(i = 0; i < size; i++)
chain[i] = NULL;
}
void insert(int value)
{
//create a newnode with value
struct node *newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = NULL;
//calculate hash key
int key = value % size;
//check if chain[key] is empty
if(chain[key] == NULL)
chain[key] = newNode;
//collision
else
{
//add the node at the end of chain[key].
struct node *temp = chain[key];
while(temp->next)
{
temp = temp->next;
}
temp->next = newNode;
}
}
void print()
{
int i;
printf("chain[%d]-->",i);
while(temp)
{
printf("%d -->",temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}
int main()
{
//init array of list to NULL
init();
insert(7);
insert(0);
insert(3);
insert(10);
insert(4);
insert(5);
print();
return 0;
}
Output:
chain[0]-->7 -->0 -->NULL
chain[1]-->NULL
chain[2]-->NULL
chain[3]-->3 -->10 -->NULL
chain[4]-->4 -->NULL
chain[5]-->5 -->NULL
chain[6]-->NULL
Information Technology
Open Addressing
#include <stdio.h>
#include <conio.h>
void display(int a[], int n)
{
int i;
// Displaying complete hash table
for (i = 0; i < n; i++)
{
printf("\n %d %d",i,a[i]);
}
}
void Linear_prob(int table[], int tsize,int num)
{
int key = num % tsize; //Computing the hash key using hash function
while (table[key]!= -1) //if empty slot is not found
{
key=(key+1)%tsize; //then move linearly dow in search of empty slot
}
table[key]=num ; //if empty slot gets then insert the element
display(table, tsize);
}
int main()
{
int SIZE = 10;// Size of the hash table
int num;
int hash_table[10];
char ans;
int i;
// Initializing the hash table
for (i=0; i < SIZE; i++)
{
hash_table[i] -1;//-1 indicates empty slot
}
do
{
printf("\nEnter The Number: ");
scanf("%d", &num); //This element is to be inserted in hash table
Linear_prob(hash_table,SIZE,num);
printf("\n Do U Wish To Continue?(y/n)");
ans = getch();
} while(ans=='y');
return 0;
}
Output
Enter The Number: 131
0 -1
1 131
Information Technology
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
Do U Wish To Continue?(y/n)
Enter The Number: 21
0 -1
1 131
2 21
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
Do U Wish To Continue? (y/n)
Enter The Number: 3
0 -1
1 131
2 21
33
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
Do U Wish To Continue? (y/n)
Enter The Number: 4
0 -1
1 131
2 21
33
44
5 -1
6 -1
7 -1
8 -1
9 -1
Do U Wish To Continue?(y/n)
Enter The Number: 5
0 -1
1 131
Information Technology
2 21
33
44
55
6 -1
7 -1
8 -1
9 -1
Do U Wish To Continue?(y/n)
Enter The Number: 8
0 -1
1 131
2 21
33
44
55
6 -1
7 -1
88
9 -1
Do U Wish To Continue?(y/n)
Enter The Number: 9
0 -1
1 131
2 21
33
44
55
6 -1
7 -1
88
99
Do U Wish To Continue?(y/n)
Enter The Number: 18
0 18
1 131
2 21
33
44
55
6 -1
7 -1
88
99
Do U Wish To Continue?(y/n)
Enter The Number: 33
0 18
1 131
Information Technology
2 21
33
44
55
6 33
7 -1
88
99
Information Technology
return temp;
}
// A utility function to create an empty Queue.
// The queue can have at most 'numberOfFrames' nodes
Queue* createQueue(int numberOfFrames)
{
Queue* queue = (Queue*)malloc(sizeof(Queue));
// The queue is empty
queue->count = 0;
queue->front = queue->rear = NULL;
// Number of frames that can be stored in memory
queue->numberOfFrames = numberOfFrames;
return queue;
}
// A utility function to create an empty Hash of given
Information Technology
// capacity
Hash* createHash(int capacity)
{
// Allocate memory for hash
Hash* hash = (Hash*)malloc(sizeof(Hash));
hash->capacity = capacity;
// Create an array of pointers for referring queue nodes
hash->array
= (QNode**)malloc(hash->capacity * sizeof(QNode*));
// Initialize all hash entries as empty
int i;
for (i = 0; i < hash->capacity; ++i)
hash->array[i] = NULL;
return hash;
}
// A function to check if there is slot available in memory
int AreAllFramesFull(Queue* queue)
{
return queue->count == queue->numberOfFrames;
}
// A utility function to check if queue is empty
int isQueueEmpty(Queue* queue)
{
return queue->rear == NULL;
}
// A utility function to delete a frame from queue
void deQueue(Queue* queue)
{
if (isQueueEmpty(queue))
return;
// If this is the only node in list, then change front
if (queue->front == queue->rear)
queue->front = NULL;
// Change rear and remove the previous rear
QNode* temp = queue->rear;
queue->rear = queue->rear->prev;
if (queue->rear)
queue->rear->next = NULL;
free(temp);
// decrement the number of full frames by 1
queue->count--;
}
// A function to add a page with given 'pageNumber' to both
// queue and hash
void Enqueue(Queue* queue, Hash* hash, unsigned pageNumber)
{
// If all frames are full, remove the page at the rear
if (AreAllFramesFull(queue)) {
Information Technology
queue->front = reqPage;
}
}
// Driver code
int main()
{
// Let cache can hold 4 pages
Queue* q = createQueue(4);
// Let 10 different pages can be requested (pages to be
// referenced are numbered from 0 to 9
Hash* hash = createHash(10);
// Let us refer pages 1, 2, 3, 1, 4, 5
ReferencePage(q, hash, 1);
ReferencePage(q, hash, 2);
ReferencePage(q, hash, 3);
ReferencePage(q, hash, 1);
ReferencePage(q, hash, 4);
ReferencePage(q, hash, 5);
// Let us print cache frames after the above referenced
// pages
printf("%d ", q->front->pageNumber);
printf("%d ", q->front->next->pageNumber);
printf("%d ", q->front->next->next->pageNumber);
printf("%d ", q->front->next->next->next->pageNumber);
return 0;
}
Output:
5413