Professional Documents
Culture Documents
BX4001
BX4001
NAME : …………………………………………........................
REG. NO : …………………………………………........................
YEAR/SEM : …………………………………………........................
BRANCH : …………………………………………........................
PGP COLLEGE OF ENGINEERING AND TECHNOLOGY
NAMAKKAL – 637 207
CERTIFICATE
List of Experiments
INDEX
EX. NO. 1 ARRAY IMPLEMENTATION OF STACK, QUEUE AND CIRCULAR QUEUE ADTS
DATE :
AIM: To implement Stack, Queue, and Circular Queue ADTs using Arrays
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{ case 1:
lOMoAR cPSD| 10518309
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
} } }
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{ if(top<=-1)
{
printf("\n\t Stack is under flow");
}
lOMoAR cPSD| 10518309
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
} else
{
printf("\n The STACK is empty");
}
}
void insert();
void delete();
void display();
lOMoAR cPSD| 10518309
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
lOMoAR cPSD| 10518309
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /* End of display() */
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: EXIT
Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear position.
}
}
// function to delete the element from the queue
int dequeue()
{
if((front==-1) && (rear==-1)) // condition to check queue is empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}
}
// function to display the elements of a queue
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
lOMoAR cPSD| 10518309
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
}
}
}
int main()
{
int choice=1,x; // variables declaration
OUTPUT 1 : STACK
Enter the size of STACK[MAX=100]:10
STACK OPERATIONS USING ARRAY
1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter the Choice:1
Enter a value to be pushed:12
Enter the Choice:1
Enter a value to be pushed:24
98
24
12
Press Next Choice
Enter the Choice:2
24
12
Press Next Choice
Enter the Choice:4
EXIT POINT
OUTPUT 2 : QUEUE
RESULT :
lOMoAR cPSD| 10518309
ALGORITHM :
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable
function calls in the main method to perform user selected operation
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
lOMoAR cPSD| 10518309
void beginsert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
printf("\nNode inserted");
}
else
lOMoAR cPSD| 10518309
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
} } }
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
} }
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted");
}}
lOMoAR cPSD| 10518309
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n"); } }
lOMoAR cPSD| 10518309
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
lOMoAR cPSD| 10518309
flag=0;
} else
{ flag=1; }
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
} } }
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values.......... \n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
} }}
OUTPUT
*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete from Beginning 9. Exit
5. Delete from last
Enter your choice?1
Enter value 7
Node inserted
lOMoAR cPSD| 10518309
*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete from Beginning 9.Exit
5. Delete from last
Enter your choice? 1
Enter value 8
Node inserted
*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete fromBeginning 9.Exit
5. Delete from last
Enter your choice?1
Enter value6
Node inserted
*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete from Beginning 9. Exit
5. Delete from last
Enter your choice?8
printing values . . . . .
6
8
7
RESULT :
lOMoAR cPSD| 10518309
EX. NO. 3 LINKED LIST IMPLEMENTATION OF STACK AND LINEAR QUEUE ADTS
DATE :
AIM :
To implement stack and linear Queue ADT using linked list in C Program
ALGORITHM 1:
Algorithm to insert an element in a linked stack
Step 1: Allocate memory for the new node and name it as NEW_NODE
Step 2: SET NEW_NODE DATA = VAL
Step 3: IF TOP = NULL
SET NEW_NODE NEXT = NULL
SET TOP =NEW_NODE
ELSE
SET NEW_NODE NEXT = TOP
SET TOP =NEW_NODE
[END OF IF]
Step 4: END
Algorithm to delete an element from a linked stack
Step 1: IF TOP = NULL PRINT “UNDERFLOW”
Goto Step 5
[END OF IF]
Step 2: SET PTR = TOP
Step 3: SET TOP = TOP NEXT
Step 4: FREE PTR
Step 5: END
PROGRAM 1:
/*
* C PROGRAM TO IMPLEMENT A STACK USING LINKED LIST
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
} *top,*top1,*temp;
int topelement();
lOMoAR cPSD| 10518309
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create empty stack */
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
lOMoAR cPSD| 10518309
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
lOMoAR cPSD| 10518309
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
int topelement()
{
return(top->info);
}
/* Check if stack is empty or not */
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
void create();
void queuesize();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
lOMoAR cPSD| 10518309
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
/* Dequeing the queue */
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
lOMoAR cPSD| 10518309
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
OUTPUT - STACK
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56
Enter choice : 1
Enter data : 80
Enter choice : 2
Popped value : 80
Enter choice : 3
Top element : 56
Enter choice : 1
Enter data : 78
Enter choice : 1
Enter data : 90
Enter choice : 6
90 78 56
Enter choice : 7
No. of elements in stack : 3
Enter choice : 8
All stack elements destroyed
Enter choice : 4
Stack is empty
Enter choice : 5
OUTPUT - QUEUE
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
lOMoAR cPSD| 10518309
Enter choice : 1
Enter data : 14
Enter choice : 1
Enter data : 85
Enter choice : 1
Enter data : 38
Enter choice : 3
Front element : 14
Enter choice : 6
14 85 38
Enter choice : 7
Queue size : 3
Enter choice : 2
Dequed value : 14
Enter choice : 6
85 38
Enter choice : 7
Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5
RESULT :
lOMoAR cPSD| 10518309
PROGRAM :
# include <stdio.h>
struct Node {
int coeff;
int pow;
struct Node* next;
};
// Function to create new node
void create_node(int x, int y, struct Node** temp)
{
struct Node *r, *z;
z = *temp;
if (z == NULL) {
r = (struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
} else {
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
lOMoAR cPSD| 10518309
OUTPUT
1st Number: 5x^2+4x^1+2x^0
2nd Number: -5x^1-5x^0
Added polynomial: 5x^2-1x^1-3x^0
RESULT :
lOMoAR cPSD| 10518309
AIM : To implement the algorithm for evaluating postfix expressions and converting infix to postfix
Conversion in C Program
/* This program is for evaluation of postfix expression. This program assume that there
are only four operators (*, /, +, -) in an expression and operand is single digit only Further
this program does not do any error handling e.g. it does not check that entered postfix
expression is valid * or not. * */
#include <stdio.h>
#include <ctype.h>
#define MAXSTACK 100 /* for max size of stack */
#define POSTFIXSIZE 100 /* define max number of charcters in postfix expression */
/* declare stack and its top pointer to be used during postfix expression evaluation*/
int stack[MAXSTACK];
int top = -1; /* because array index in C begins at 0 */
/* can be do this initialization somewhere else */
else {
top = top + 1;
stack[top] = item;
}
}
/* define pop operation */
int pop()
{
int item;
if (top < 0) {
printf("stack under flow");
}
else {
item = stack[top];
top = top - 1;
return item;
}
}
/* define function that is used to input postfix expression and to evaluate it */
void EvalPostfix(char postfix[])
{
int i;
char ch;
int val;
int A, B;
/* evaluate postfix expression */
for (i = 0; postfix[i] != ')'; i++) {
ch = postfix[i];
if (isdigit(ch)) {
/* we saw an operand,push the digit onto stack ch - '0' is used for getting digit rather
than ASCII code of digit */
push(ch - '0'); }
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
/* we saw an operator pop top element A and next-to-top elemnet B
* from stack and compute B operator A */
A = pop();
B = pop();
switch (ch) /* ch is an operator */
{
lOMoAR cPSD| 10518309
case '*':
val = B * A;
break;
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;
break;
}
/* push the value obtained above onto the stack */
push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
int main()
{
int i;
/* declare character array to store postfix expression */
char postfix[POSTFIXSIZE];
printf("ASSUMPTION: There are only four operators(*, /, +, -) in an expression and operand is
single digit only.\n");
printf(" \nEnter postfix expression,\npress right parenthesis ')' for end expression : ");
/* take input of postfix expression from user */
for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
if (postfix[i] == ')') /* is there any way to eliminate this if */
{
break;
} /* and break statement */
}
/* call function to evaluate postfix expression */
EvalPostfix(postfix);
return 0;
}
lOMoAR cPSD| 10518309
Second Run:
Enter Infix expression : (3^2*5)/(3*2-3)+5
Postfix Expression: 32^5*32*3-/5+
RESULT :
lOMoAR cPSD| 10518309
AIM : To implement Binary search trees and its operations using C Program
ALGORITHM :
A BST is a binary tree of nodes ordered in the following way:
1. Each node contains one key (also unique)
2. The keys in the left subtree are < (less) than the key in its parent node
3. The keys in the right subtree > (greater) than the key in its parent node
4. Duplicate node keys are not allowed.
5. Inserting a node
Insert(N, T) = N if T is empty
= insert(N, T.left) if N < T
= insert(N, T.right) if N > T
6. Searching for a node
Search(N, T) = false if T is empty
= true if T = N
= search(N, T.left) if N < T
= search(N, T.right) if N > T
7. Deleting a node
8. Traversing a BST
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: Write TREE DATA
Step 3: PREORDER(TREE LEFT)
Step 4: PREORDER(TREE RIGHT)
[END OF LOOP]
Step 5: END
PROGRAM
/* C program to implement the Binary Search Tree */
#include <stdio.h>
#include <stdlib.h>
// structure of a node
struct node
{
int data;
struct node *left;
struct node *right;
};
// globally initialized root pointer
struct node *root = NULL;
// function prototyping
lOMoAR cPSD| 10518309
case 2:
data = get_data();
root = delete(root, data);
break;
case 3:
data = get_data();
if (search(data) == 1)
{ printf("\nData was found!\n"); }
else
{ printf("\nData does not found!\n"); }
break;
case 4:
result = largest_node(root);
if (result != NULL)
{ printf("\nLargest Data: %d\n", result->data); }
break;
case 5:
result = smallest_node(root);
if (result != NULL)
{ printf("\nSmallest Data: %d\n", result->data); }
break;
case 6:
inorder(root);
break;
case 7:
postorder(root);
break;
case 8:
preorder(root);
break;
case 9:
printf("\n\nProgram was terminated\n");
break;
default:
printf("\n\tInvalid Choice\n");
break; }
printf("\n \nDo you want to continue? ");
fflush(stdin);
scanf(" %c", &userActive);
lOMoAR cPSD| 10518309
} return 0; }
// creates a new node
struct node *create_node(int data)
{
struct node *new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{ printf("\nMemory for new node can't be allocated");
return NULL; }
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void insert(int data) // inserts the data in the BST
{
struct node *new_node = create_node(data);
if (new_node != NULL)
{ // if the root is empty then make a new node as the root node
if (root == NULL)
{ root = new_node;
printf("\n* node having data %d was inserted\n", data);
return; }
struct node *temp = root;
struct node *prev = NULL;
// traverse through the BST to get the correct position for insertion
while (temp != NULL)
{ prev = temp;
if (data > temp->data)
{ temp = temp->right; }
else
{ temp = temp->left; } }
// found the last node where the new node should insert
if (data > prev->data)
{ prev->right = new_node; }
else
{ prev->left = new_node; }
printf("\n* node having data %d was inserted\n", data);
} }
lOMoAR cPSD| 10518309
struct node *delete (struct node *root, int key) // deletes the given key node from the BST
{
if (root == NULL)
{ return root; }
if (key < root->data)
{ root->left = delete (root->left, key); }
else if (key > root->data)
{ root->right = delete (root->right, key); }
else
{ if (root->left == NULL)
{ struct node *temp = root->right;
free(root);
return temp; }
else if (root->right == NULL)
{ struct node *temp = root->left;
free(root);
return temp; }
struct node *temp = smallest_node(root->right);
root->data = temp->data;
root->right = delete (root->right, temp->data);
} return root; }
// search the given key node in BST
int search(int key)
{
struct node *temp = root;
while (temp != NULL)
{ if (key == temp->data)
{ return 1; }
else if (key > temp->data)
{ temp = temp->right; }
else
{ temp = temp->left; } }
return 0; }
// finds the node with the smallest value in BST
struct node *smallest_node(struct node *root)
{ struct node *curr = root;
while (curr != NULL && curr->left != NULL)
{ curr = curr->left; } return curr; }
lOMoAR cPSD| 10518309
struct node *largest_node(struct node *root) // finds the node with the largest value in BST
{
struct node *curr = root;
while (curr != NULL && curr->right != NULL)
{ curr = curr->right; }
return curr;
}
void inorder(struct node *root) // inorder traversal of the BST
{
if (root == NULL)
{ return; }
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void preorder(struct node *root) // preorder traversal of the BST
{
if (root == NULL)
{ return; }
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(struct node *root) // postorder travsersal of the BST
{
if (root == NULL)
{ return; }
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
// getting data from the user
int get_data()
{
int data;
printf("\nEnter Data: ");
scanf("%d", &data);
return data;
}
lOMoAR cPSD| 10518309
OUTPUT :
1. Insert
. Delete
3. Search
4. Get Larger Node Data
5. Get smaller Node data
====Traversals=====
6. Inorder
7. Post Order
8. Pre Oder
9. Exit
Enter Your Choice: 6
RESULT:
lOMoAR cPSD| 10518309
ALGORITHM
This algorithm creates spanning tree with minimum weight from a given weighted graph.
1. Begin
2. Create edge list of given graph, with their weights.
3. Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
5. Add other edges. While adding an edge take care that the one end of the edge should
always be in the skeleton tree and its cost should be minimum.
6. Repeat step 5 until n-1 edges are added.
7. Return.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
lOMoAR cPSD| 10518309
return 0;
}
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{ if(G[i][j]==
0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
lOMoAR cPSD| 10518309
OUTPUT
Enter no. of vertices:6
Enter the adjacency matrix:
031600
305030
150564
605002
036006
004260
spanning tree matrix:
031000
300030
100004
000002
030000
004200
Total cost of spanning tree=13
RESULT :
lOMoAR cPSD| 10518309
AIM :
To implement linear search and binary search algorithm using C Program
ALGORITHM :
Algorithm for Linear Search
STEP 1 : Initially accept the element to be searched from the user.
STEP 2: Then, we create a for loop and start searching for the element in a sequential fashion.
STEP 3 : if match is encountered i.e. array[element] == key value, return the element along with
its position in the array.
STEP 4 : If no values are found that match the input, it returns -1.
Algorithm for Binary Search
Step 1 : Find the middle element of array using middle = initial_value + end_value / 2 ;
Step 2 : If middle = element, return „element found‟ and index.
Step 3 : if middle > element, call the function with end_value = middle - 1 .
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.
switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2: binary_search(search_key,array,n);
break;
default:
exit(0);
}
getch();
return 0;
}
/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{
/*Declare Variable */
int i,location;
for(i=1;i<=n;i++)
{
if(search_key == array[i])
{
location = i;
printf(" \n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf(" \n");
}}}
/* Binary Search to find Search Key */
void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high; low = 1; high = n;
mid = (low + high)/2; i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1; high = mid+1;
mid = (low+high)/2;
}
lOMoAR cPSD| 10518309
else {
low = mid+1; high = n;
mid = (low+high)/2;
}}
printf(" \n");
printf("location=%d\t",mid); printf("Search_Key=%d Found!\n",search_key);
printf(" \n");
}
OUTPUT :
ENTER THE SIZE OF THE ARRAY:6
ENTER THE ELEMENTS OF THE ARRAY: 45 6 86 23 64 77
ENTER THE SEARCH KEY:86
1. LINEAR SEARCH
2. BINARY SEARCH
ENTER YOUR CHOICE:2
Location =3
Search_Key = 86
Found!
RESULT :
lOMoAR cPSD| 10518309
DATE :
ALGORITHM :
Algorithm for Insertion Sort
Step 1 − If the element is the first one, it is already sorted.
Step 2 – Move to next element
Step 3 − Compare the current element with all elements in the sorted array
Step 4 – If the element in the sorted array is smaller than the current element, iterate to
the next element. Otherwise, shift all the greater element in the array by one
position towards the right
Step 5 − Insert the value at the correct position
Step 6 − Repeat until the complete list is sorted
Algorithm for Selection Sort:
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process
printf("n");
}
OUTPUT :
Enter number of elements 5
Enter 5 Numbers
78
56
-23
45
9
Sorted Array:
-23 9 45 56 78
RESULT:
lOMoAR cPSD| 10518309
ALGORITHM :
Step 1 : MergeSort(arr[], l, r), where l is the index of the first element & r is the index of
the last element. If r > l
Step 2: Find the middle index of the array to divide it in two halves: m = (l+r)/2
Step 3: Call MergeSort for first half: mergeSort(array, l, m)
Step 4. Call mergeSort for second half: mergeSort(array, m+1, r)
Step 5. Recursively, merge the two halves in a sorted manner, so that only one sorted
array is left: merge(array, l, m, r)
PROGRAM :
#include<stdio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{ mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
} }
lOMoAR cPSD| 10518309
OUTPUT :
Enter number of elements 5
Enter 5 Numbers
78
56
-23
45
9
Sorted Array:
-23 9 45 56 78
RESULT :
lOMoAR cPSD| 10518309
AIM :
To implement Linear probing and Quadratic Probing techniques of Open Addressing
ALGORITHM
Define a node, structure say HashNode, to a key-value pair to be hashed.
Initialize an array of the pointer of type HashNode, say *arr[] to store all key-value pairs.
Insert(Key, Value): Insert the pair {Key, Value} in the Hash Table.
Initialize a HashNode variable, say temp, with value {Key, Value}.
Find the index where the key can be stored using the, Hash Function and then
store the index in a variable say HashIndex.
If arr[HashIndex] is not empty or there exists another Key, then do linear
probing by continuously updating the HashIndex as HashIndex
=(HashIndex+1)%capacity.
If arr[HashIndex] is not null, then insert the given Node by assigning the
address of temp to arr[HashIndex].
Find(Key): Finds the value of the Key in the Hash Table.
Find the index where the key may exist using a Hash Function and then store
the index in a variable, say HashIndex.
If the arr[HashIndex] contains the key, Key then returns the value of it.
Otherwise, do linear probing by continuously updating
the HashIndex as HashIndex =(HashIndex+1)%capacity. Then, if Key is
found, then return the value of the Key at that HashIndex and then return true.
If the Key is not found, then return -1 representing not found. Otherwise, return
the value of the Key.
Delete(Key): Deletes the Key from the Hash Table.
Find the index where the key may exist using a Hash Function and then store
the index in a variable, say HashIndex.
If the arr[HashIndex] contains the key, Key then delete by assigning {-1, -
1} to the arr[HashIndex] and then return true.
Otherwise, do linear probing by continuously updating
the HashIndex as HashIndex =(HashIndex+1)%capacity. Then, if Key is
found then delete the value of the Key at that HashIndex and then return true.
If the Key is not found, then the return is false.
lOMoAR cPSD| 10518309
PROGRAM
#include <stdio.h>
#include <conio.h>
int tsize;
int hasht(int key)
{
int i ;
i = key%tsize ;
return i;
}
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
printf ("\nEnter the number of elements: ");
scanf ("%d",&n);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements: ");
for (i=0;i<n;i++)
{ scanf("%d",&arr[i]); }
do
{
lOMoAR cPSD| 10518309
OUTPUT
Enter the size of the hash table: 10
Enter the number of elements: 8
Enter Elements: 72 27 36 24 63 81 92 101
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1
The elements in the array are:
Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 92
Element at position 6: 36
Element at position 7: 27
Element at position 8: 101
Element at position 9: -1
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2
The elements in the array are:
Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 101
Element at position 6: 36
Element at position 7: 27
Element at position 8: 92
Element at position 9: -1
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 3
RESULT:
lOMoAR cPSD| 10518309
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct queue
{ int size;
int f;
int r;
int* arr; };
int isEmpty(struct queue
*q){ if(q->r==q->f) {
return 1;
} return 0; }
int isFull(struct queue
*q){ if(q->r==q->size-
1){
return 1; }
return 0; }
void enqueue(struct queue *q, int
val){ if(isFull(q)){
printf("This Queue is full\n"); }
else{
q->r++;
q->arr[q->r] = val;
// printf("Enqued element: %d\n", val);
} }
int dequeue(struct queue
*q){ int a = -1;
if(isEmpty(q)){
printf("This Queue is empty\n");
lOMoAR cPSD| 10518309
} else
{ q-
>f++;
a = q->arr[q->f];
} return a;
}
int main(){
// Initializing Queue (Array Implementation)
struct queue q;
q.size = 400;
q.f = q.r = 0;
q.arr = (int*) malloc(q.size*sizeof(int));
// BFS Implementation
int node;
int i = 1;
int visited[7] = {0,0,0,0,0,0,0};
int a [7][7] = {
{0,1,1,1,0,0,0},
{1,0,1,0,0,0,0},
{1,1,0,1,1,0,0},
{1,0,1,0,1,0,0},
{0,0,1,1,0,1,1},
{0,0,0,0,1,0,0},
{0,0,0,0,1,0,0}
};
printf("%d", i);
visited[i] = 1;
enqueue(&q, i); // Enqueue i for exploration
while (!isEmpty(&q))
{
int node = dequeue(&q);
for (int j = 0; j < 7; j++)
{
if(a[node][j] ==1 && visited[j] ==
0){ printf("%d", j);
visited[j] = 1;
enqueue(&q, j);
}
} }
return 0; }
lOMoAR cPSD| 10518309
OUTPUT :
1023456
RESULT :
lOMoAR cPSD| 10518309
ALGORITHM :
1. Store each vertex‟s In-Degree in an array D
2. Initialize queue with all “in-degree=0” vertices
3. While there are vertices remaining in the queue:
(a) Dequeue and output a vertex
(b) Reduce In-Degree of all vertices adjacent to it by 1
(c) Enqueue any of these vertices whose In-Degree became zero
4. If all vertices are output then success, otherwise there is a cycle.
PROGRAM :
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++){ i
ndeg[i]=0;
flag[i]=0; }
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
flag [k]=1;
}
lOMoAR cPSD| 10518309
for(i=0;i<n;i++){ if(
a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}
OUTPUT :
Enter the no of vertices:
3
Enter the adjacency matrix:
Enter row 1
1
2
3
Enter row 2
1
2
3
Enter row 3
1
2
3
The topological order is:1
RESULT: