Rajalakshmi: Cs19241-Data Structuress
Rajalakshmi: Cs19241-Data Structuress
RAJALAKSHMI
ENGINEERING COLLEGE
An AUTONOMOUS Institution
Afmliated to ANNA UNIVERSITY, Chennai
CS19241-DATA STRUCTURESs
LABORATORY NOTE BOOK
aeHaninaMuugn
Year/Branch/Scction:.. Ja/Al 2ML
University Register No. : d1501013.. *****************
Semester L.
Academic Ycar
RAJALAKSHMI
ENGINEERING COLLEGE
Ad a UNV .
BONAFIDE CERTIFICATE
UNIVEKSTY REGISTER o
2015010133
d te
GSi124-aba
bonafie veard of wrk one by de dbe suakent in the
dbvucbau Laboratory during the year 20d0202l
INDEX
S.NO DATE TOPIC
PGNO. SIGNATURE
234
2021Revsca Strng using Stack.
223.42021 Balancing Paranthesis using Stack:
3 . 7.5.2021 n s to Postn
co
75.2021 Evaluation of Postfix Expression
th
0 T0 pick up the
last job in
List.
285.2021 Sort the aay in incrcasing order and print out
the original indes position of the new sorted Lb
14
1.6.2021 Copy the clements of one List
siTng Lmkeu LB
to anothr
Lis5A
15. 11.2021Sum of two polynonmia u s 60
16.
25.6.2021Dilerentiation o poynoa
cu
he
6
Lmked List.
using Singy
17 25.62021Implcmentation of Tree Traversal. F0
18. 2.7.2021 Implementation of Binary Search Tree 15
19. 2.72021 Implementation of Binary Heap. 0
20. 9.7.2021 Implementation of Depth Finst Search.
4
21. 9.7 2021 Implementation of Breadth Finst Scarch 81
22 16.7.2021 Implementation of Topological sort.
90
23. 16.7.2021 Implernentation of Merge Sor. 15
Implementation of Quick Sort
24. 23.7.2021
25 23.72021 Implementation of Hashing
Ex.No.1 REVERSE A STRING USING STACK
DATE:23-04-2021
AIM
PROBLEM STATEMENT
ABC international is checking the company names of its client for palindrome. A string is
said to be palindrome if both the input string and the reversed output string are one and
the same. So ABC international needs to reverse the names of the companies they have.
Write a program to reverse a string using stack implementation. Remember as stack
uses LIFO concept the string pushed can be popped out in a reverse order.
For example:
Input Result
Hello olleH
ABCDEFGHIJKL Overflow
ALGORITHM
Step 1: Start
Step 2: Get the string as characters through a for loop.
Step 3: Push the characters into the stack using an user defined function named push()
Step 4: After pushing all the characters into the stack, pop them all out by another function
1
named pop()
Step 5: Print the characters immediately after popping each of them
Step 6: The string thus printed will give the reversed form of the given string
Step 7:Stop
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define size 10
char stack[size];
int top = -1;
int isFull()
{
if(top == size-1)
return 1;
else
return 0;
}
int isEmpty()
{
if(top == -1)
return 1;
else
return 0;
}
char pop()
{
if(isEmpty())
2
{
printf("Underflow");
exit(0);
}
else
{
return stack[top--];
}
}
int main()
{
int i;
char str[10];
scanf("%s",str);
for(i = 0;i<strlen(str);i++)
push(str[i]);
while(!isEmpty())
{
printf("%c",pop());
}
}
OUTPUT
RESULT
The program to reverse a string using stack has been successfully executed
3
Ex.No.2 BALANCE PARANTHESIS USING STACK
DATE:23-04-2021
AIM
PROBLEM STATEMENT
To evaluate the expression, the parenthesis need to be balanced which means all open
parenthesis should have a closed parenthesis. Write a program using stack data structure to
check whether the given parenthesis string is balanced or not.
Input: String with parenthesis
Output: String is “Balanced” or “Not Balanced”
For example:
Input Result
ALGORITHM
Step 1: Start
Step 2: Get the expression as characters using a for loop
Step 3: Push all the parentheses of the expression into the stack using an
user defined function named push()
Step 4: Pop the characters one by one inside a for loop
Step 5: If the popped character is an open parenthesis increase ‘o’ count by 1
Step 6: If the popped character is a closed parenthesis increase ‘c’ count by 1
Step 7: After popping all the characters check if ‘o==c’
Step 8: If it is true, print “Balanced”
Step 9: Else, “Unbalanced”.
Step 10: Stop
4
PROGRAM
#include <stdio.h>
#include <string.h>
#define MAX 20
char Stack[MAX];
int top = -1;
int IsEmpty();
void Push(char sym);
char Pop();
int main()
{
char exp[20], c;
int i;
scanf("%s", exp);
for(i = 0; i < strlen(exp); i++)
{
if(exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
{
Push(exp[i]);
}
else if((exp[i]==')'||exp[i]==']'||exp[i]=='}')&&IsEmpty())
{
printf("Not Balanced");
return 0;
}
else if(exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
{
c = Pop();
if(c == '(' && exp[i] != ')')
{
printf("Not Balanced");
return 0;
}
else if(c == '[' && exp[i] != ']')
{
printf("Not Balanced");
return 0;
}
else if(c == '{' && exp[i] != '}')
{
printf("Not Balanced");
return 0;
}
}
}
if(!IsEmpty())
printf("Not Balanced");
else
5
printf("Balanced");
return 0;
}
int IsEmpty()
{
if(top == -1)
return 1;
else
return 0;
}
void Push(char sym)
{
Stack[++top] = sym;
}
char Pop()
{
return Stack[top--];
}
OUTPUT
RESULT
The program to balance paranthesis using stack has been successfully executed
6
Ex.No.3 INFIX TO POSTFIX CONVERSION USING STACK
DATE:07-05-2021
AIM
PROBLEM STATEMENT
Give an input Infix Expression, write the program to convert the given infix expression to
postfix expression using Stack Operations.
Input : Infix Expression
Output : Postfix Expression
For example:
Input Result
a+b*c abc*+
ALGORITHM
Step 1: Start
Step 2: Scan the Infix Expression from left to right
Step 3: If the scanned character is an operand, append it with final Infix to
Postfix string
Step 4: Else,If the precedence order of the scanned(incoming)
operator is greater than the precedence order of the operator in
the stack (or the stack is empty or the stack contains a ‘(‘ or ‘[‘ or
‘{‘), push it on stack.
Step 5: Else, Pop all the operators from the stack which are
greater than or equal to in precedence than that of the scanned
operator. After doing that Push the scanned operator to the stack.
(If you encounter parenthesis while popping then stop there and
push the scanned operator in the stack
Step 6: If the scanned character is an ‘(‘or ‘[‘or ‘{‘, push it to the stack
Step 7: If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and and output it until a
‘(‘or ‘[‘or ‘{‘respectively is encountered, and discard both the parenthesis
7
Step 8: Repeat steps 2-6 until the infix expression is scanned.
PROGRAM
#include<stdio.h>
#include<string.h>
#define MAX 20
int Stack[MAX], top = -1;
char expr[MAX], post[MAX];
int main()
{
int i;
fgets(expr,sizeof(expr),stdin);
for(i = 0; i < strlen(expr); i++)
{
if(expr[i] >= 'a' && expr[i] <= 'z')
{
printf("%c", expr[i]);
}
else if(expr[i] == '(')
{
Push(expr[i]);
}
else if(expr[i] == ')')
{
while(Top() != '(')
printf("%c", Pop());
Pop();
}
else
{
while(Priority(expr[i])<=Priority(Top()) && top!=-1)
printf("%c", Pop());
Push(expr[i]);
}
}
8
for(i = top; i >= 0; i--)
{
printf("%c", Pop());
}
return 0;
}
char Pop()
{
char e;
e = Stack[top];
top = top - 1;
return e;
}
char Top()
{
return Stack[top];
}
9
}
OUTPUT
RESULT
The program to convert infix to postfix using stack has been successfully executed
10
Ex.No.4 EVALUATION OF POSTFIX EXPRESSION
DATE:07-05-2021
AIM
PROBLEM STATEMENT
Give an input Postfix Expression, write the program to evaluate the given postfix expression
using Stack Operations.
Input : Postfix Expression and List of values of the variables
Output : Result of the expression
For example:
Result
Input
abc+*d* 70
2
3
4
5
ALGORITHM
Step 1: Start
Step 2: Make an empty stack
Step 3: Read the postfix expression one character at a time until it encounters
the end of expression
Step 4: If the character is an operand, push its associated value onto the stack
Step 5: If the character is an operator, pop two values from the stack, apply the operator to them
and push the result onto the stack
Step 6: Stop
11
PROGRAM
#include <stdio.h>
#include <string.h>
#define MAX 20
int Stack[MAX]; int top = -1;
char expr[MAX];
void Push(int ele);
int Pop();
int main()
{
int i, a, b, c, e;
scanf("%s",expr);
for(i = 0; i < strlen(expr); i++)
{
if(expr[i]=='+'||expr[i]=='-'||expr[i]=='*'||expr[i]=='/')
{
b = Pop();a = Pop();
switch(expr[i])
{
case '+':
c = a + b;
Push(c);
break;
case '-':
c = a - b;
Push(c);
break;
case '*':
c = a * b;
Push(c);
break;
12
case '/':
c = a / b;
Push(c);
break;}
}
else
{
scanf("%d", &e);
Push(e);
}
}
printf("%d",Pop());
return 0;
}
void Push(int ele)
{
top = top + 1;
Stack[top] = ele;
}
int Pop()
{
int e;
e = Stack[top];
top = top - 1;
return e;
}
13
OUTPUT
abc+*d* 70 70
2
3
4
5
ab*cde/-+ 21 21
4
5
5
8
2
RESULT
14
Ex.No.5 TO PICK UP THE LAST JOB IN THE QUEUE
DATE:21-05-2021
AIM
PROBLEM STATEMENT
For example:
Input Result
4 close
Open open close close
ALGORITHM
Step 1: Start
Step 4: Int n
Step 5: Char c
Step 6:Read n
Step 8: r++
15
Step 10: Display q[r]
PROGRAM
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int front=-1,rear=-1;
int size;
char queue[20][20];
int isFull()
{
if(rear == size -1)
return 1;
else
return 0;
}
return 0;
}
int main()
{
char input_v[20];
scanf("%d",&size);
for(int i=0;i<size;i++)
{
scanf("%s",input_v);
enqueue(input_v);
}
16
printf("%s",queue[rear]);
return 0;
}
OUTPUT
5 close Close
Print edit delete open close
4 close Close
Open open close close
3 Rename Rename
Delete open Rename
RESULT
The program to pick up the last job in the queue has been successfully executed
17
Ex.No.6 TO PRINT THE FIRST FILE IN THE PRINTER QUEUE
DATE:21-05-2021
AIM
PROBLEM STATEMENT
The printer Queue uses the queue concept to store the list of files they get to print in the
printer. Write a program to print the first file in the printer Queue. If the no of print files is
more than the print queue size, it should say “overflow” otherwise print the name of the first
file.
Input:
Queue size n , no of inputs m and input file names
Output: names of the first file in the queue to be printed or overflow
For example:
Input Result
4 Stack
4
Stack Queue List Array
ALGORITHM
Step 1: Start
Step 4: Declare and define a void return type function – push with parameters int n and char
a[], to add element to the queue
c. Increment r by 1
18
d. For i=0 to a[i]!=’\0’, Assign a[i] to queue[r][i]
Step 5: Declare and define a char* return type function – pop with parameter int n, to display
the queue element
a. Return queue[f++]
a. Declare two integers n, m and two character arrays a[] and b[]
e. For i=0 to a[i]!=’\0’ if a[i] is equal to ‘ ‘ and I is not equal to 0, Assign b[x] as ‘\0’,
Call push(n,b), Assign x as 0, Else if a[i] is not equal to ‘ ‘, Assign b[x] as a[i], increment
x by 1
g. Call push(n,b)
Step 7: Stop
PROGRAM
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int front=-1,rear=-1;
int size, psize;
char queue[20][20];
int isFull()
{
if(rear == size -1)
return 1;
else
return 0;
}
19
int enqueue(char ch[20])
{
if(isFull())
{
printf("Overflow");
exit(0);
}
else
{
rear = rear + 1;
strcpy(queue[rear],ch);
if(front == -1)
front = 0;
}
return 0;
}
int main()
{
char input_v[20];
scanf("%d",&size);
scanf("%d",&psize);
for(int i=0;i<size;i++)
{
scanf("%s",input_v);
enqueue(input_v);
}
if (psize>size) {
printf("Overflow");
}
else {
printf("%s",queue[0]);
}
return 0;
}
20
OUTPUT
Sample1 Sample1
5
5
Sample1 Sample2 Sample3 Sample4 Sample5
4 Stack Stack
4
Stack Queue List Array
2 Overflow Overflow
3
Welcome Hello Hai
RESULT
The program to print the first file in the printer queue has been successfully executed
21
Ex.No.7 PRINT THE COUNT OF SAME VALUE IN TWO LINKED LIST
DATE:28-05-2021
AIM
Write a program to print the count of same value in two linked list
PROBLEM STATEMENT
There are N students in a class. Students having two arrears are given the chance to appear
for re-exam to clear those subjects in the same semester. Students can select subject1 or
subject2 or both. Find the number of students who registered for both subjects.
Input:
1. The first line of the input contains a single integer N denoting the number of students.
2. The second line contains N space-separated positive integers represents array subject1.
3. The second line contains N space-separated positive integers represents array subject2.
Output: Print the count of students who registered for both subjects.
Constraints:
1. 1 <= N <= 100000
2. 1 <= subject1[i] <= 100000
3. 1 <= subject2[i] <= 100000
Sample Input 1
Input:
5
12345
34567
Output:
3
Sample Input 2
Input:
10
21 41 56 78 97 63 51 22 54 87
12 10 9 45 32 65 98 51 41 78
Output:
2
22
For example:
Input Result
10 3
21 41 56 78 97 63 51 22 54 87
12 10 9 45 32 65 98 51 41 78
ALGORITHM
Step 1: Start
Step 3: Read each element of the 1st array and insert it in the 1st list
Step 4: Read each element of the 2nd array and insert it in the 2nd list
c. STEP 3: Check whether x is equal to any of the elements of the 2nd list.
f. STEP 5: Continue with the next element of the 1st list until it reaches the End
Step 7: Stop
PROGRAM
#include<stdio.h>
void insert(int *a, int n)
{
for(int i=0;i<n;i++)
{
scanf("%d",(a+i));
}
}
23
int count(int a[100000],int b[100000],int n)
{
int i,j,c=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i] == b[j])
{
c++;
}
}
}
return c;
}
int main()
{
int sub1[100000],sub2[100000];
int n,c;
scanf("%d",&n);
insert(sub1,n);
insert(sub2,n);
c = count(sub1,sub2,n);
printf("%d",c);
return 0;
OUTPUT
5 3 3
1 2 3 4 5
3 4 5 6 7
10 3 3
21 41 56 78 97 63 51 22 54 87
12 10 9 45 32 65 98 51 41 78
5 0 0
1 2 3 4 54
12 32 8 9 10
24
RESULT
The program to print the count of same value in two linked list has been successfully excexuted
25
Ex.No.8 SORT THE ARRAY IN INCREASING ORDER AND PRINT OUT THE
ORIGINAL INDEX POSITION OF THE NEW SORTED ARRAY
DATE:28-05-2021
AIM
Write a program to the array in increasing order and print out the original index position of the
new sorted array
PROBLEM STATEMENT
Students of class CSE are given an array A of positive integers of size N. The student’s task
is to sort the array in increasing order and print out the original index position of the new
sorted array.
NOTE: The indexing of the array starts with 0.
Example:
A={4,5,3,7,1}
After sorting the new array becomes A={1,3,4,5,7}.
The required output should be "4 2 0 1 3"
INPUT :
The first line of input consists of the size of the array A
The next line consists of the array of size N
OUTPUT :
Output consists of a single line of integers
CONSTRAINTS:
1<=N<=10^6
0<=A[i]<=10^6
Sample Input 1
Input:
5
12 3 87 14
65
Output:
10342
26
Sample Input 2
Input:
7
12 23 32 45 56 67
89
Output:
0123456
For example:
Input Result
5 1 0 3 4 2
12 3 87 14 65
ALGORITHM
Step 1: Start
a. Declare an array arr of size n and copy the list elements to the
b. array arr
i. Continue with the next element of the array until it reaches the end.
a. Start
27
b. Read the number of elements as n
Step 4: Stop
PROGRAM
#include<stdio.h>
void sort(int * b,int n)
{
int t;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(*(b+i) > *(b+j))
{
t = *(b+i);
*(b+i) = *(b+j);
*(b+j) = t;
}
}
}
}
scanf("%d",&n);
insert(a,n);
copy(a,b,n);
sort(b,n);
index_value(a,b,n);
return 0;
}
OUTPUT
5 1 0 3 4 2 1 0 3 4 2
12 3 87 14 65
7 0 1 2 3 4 5 6 0 1 2 3 4 5 6
12 23 32 45 56 67 89
10 9 6 8 0 1 3 4 7 5 9 6 8 0 1 3 4 7 5
1001 1056 8753 2187 3298 6547 108 3714 2 2
122 12
5 0 4 2 3 1 0 4 2 3 1
23 32000 14325 27896 5432
RESULT
The program to the array in increasing order and print out the original index position of the new
sorted array has been successfully executed
29
Ex.No.9 IMPLEMENTATION OF CIRCULAR LINKED LIST
DATE:28-05-2021
AIM
PROBLEM STATEMENT
Write a Program to implement Circular Linked List which performs the following operations
based on the users input.
1 -> Insertion
2 -> Deletion
3 -> Display
4 -> Find the Number of Elements
5 -> EXIT
For example:
Input Result
1 10 1 20 1 30 1 40 3 4 2 20 4 5 10 20 30 40
4
3
ALGORITHM
Step 1: Start
Step 2: Create a structure node as Node with int element and self referential pointer next.
30
• Until pos->next is not list print the element and change pos as pos->next.
• Until pos->next is not list and pos->next->element is not e change pos as pos->next.
• Else assign list to a new Node position Change position as position->next until
position->next is not list.
• Else
c. Until Position->next is not list increment tot by 1 and set Position as Position-
31
>next d. Print tot.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int element;
struct node * next;
}Node;
34
OUTPUT
1 10 1 20 1 30 1 40 3 4 2 20 4 5 10 20 30 40 10 20 30 40
4 4
3 3
RESULT
The program to implement circular linked list has been successfully executed
35
Ex.No.10 PRINT THE LIST IN REVERSE ORDER
DATE:04-06-2021
AIM
PROBLEM STATEMENT
In a goods train, all the wagons attached to the train have a sheet of paper pasted that tells
how much is the total weight of the goods in each wagon. The first wagon is attached to the
engine, the second wagon is attached to the first wagon and so on and the last one is guard
van. Given the weights of goods in the wagon as input, print the weights in the reverse order.
Example
If the weights of the wagons starting from wagon 1 are as follows- 100->200->300->NULL
then print the weights in the following order 300->200->100->NULL
Input Format
The first line contains an integer n, the number of elements in the linked list.
Each of the next n, lines contains an integer, the data values of the elements in the linked list.
Constraints
• 1 <=n <= 1000
• 1 <= list[i] <= 1000, where list[i] is the ith element in the list.
Sample Input
5
1
2
3
4
5
Sample Output
54321
Explanation
The initial linked list is: 1->2->3->4->5
The reversed linked list is: 5->4->3->2->1
36
For example:
Input Result
5 5
1 4
2 3
3 2
4 1
5
ALGORITHM
Step 1: START.
Step 2: input n.
Step 3: Execute for loop,until i is greater than n,if true gotostep 4,else goto step 10.
Step 6:If next position of list is NULL,goto step 7,else goto step 8.
Step 1: START.
37
Step 4: Execute while loop until next of position is null,goto step 5.
Step 9: STOP.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
typedef struct node Node;
int isEmpty(Node *List)
{
if(List->next == NULL)
return 1;
else
return 0;
}
void insert(Node *List ,int e)
{
Node *Position;
Node *newnode = malloc(sizeof(Node));
newnode->data = e;
newnode->next = NULL;
38
if(isEmpty(List))
{
newnode->prev = List;
List->next = newnode;
}
else
{
Position = List;
while(Position->next != NULL)
Position = Position->next;
newnode->prev = Position;
Position->next = newnode;
}
}
void display(Node *List)
{
Node *Position;
if(!isEmpty(List))
{
Position = List;
while(Position->next != NULL)
Position = Position->next;
while(Position != List)
{
printf("%d\n",Position->data);
Position = Position->prev;
}
}
}
int main()
{
39
int n,a;
Node *List = malloc(sizeof(Node));
List->next = NULL;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a);
insert(List,a);
}
display(List);
return 0;
}
OUTPUT
5 5 5
1 4 4
2 3 3
3 2 2
4 1 1
5
3 390 390
330 440 440
440 330 330
390
10 499 499
300 408 408
310 315 315
400 300 300
305 450 450
335 335 335
450 305 305
300 400 400
315 310 310
408 300 300
499
40
RESULT
The program to print the list in reverse has been successfully executed
41
Ex.No.11 PRINT THE TOTAL VALUE OF THE LINKED LIST
DATE:04-06-2021
AIM
PROBLEM STATEMENT
A lady gardener collects roses from garden and puts them into bags. After filling bag1, she
takes bag2 and fills with roses and so on. Later she counts the roses in each bag. Given the
count of roses in each bag as data part of a linked list, print the total count of roses found in
all bags.
Example
If the roses in each bags has the following counts- 100->115->105 the print the output as 320
Input Format
The first line contains an integer n, the number of bags.
Each of the next n, lines contains an integer, that represents the count of roses in each bag
Sample Input
3
100
115
105
Sample Output
320
For example:
Input Result
3 320
100
115
105
3 37
10
15
12
42
ALGORITHM
Step 1 : Start.
Step 8: Stop.
Step 4: Execute while loop,where it runs until the next of position reaches NULL,if true goto
step 5,else goto
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int e;
struct node *next;
43
};
typedef struct node n;
void insert(n *list,int e)
{
n *temp = malloc(sizeof(struct node ));
temp -> e = e;
temp -> next = NULL;
n *p;
p = list;
if(p -> next == NULL)
{
p -> next = temp;
}
else
{
while(p -> next != NULL)
{
p = p -> next;
}
p -> next = temp;
}
}
void show_sum(n *list)
{
n *p;
p = list;
int sum;
while(p -> next != NULL)
{
p = p-> next;
sum = p -> e + sum;
}
printf("%d",sum);
}
int main()
{
n * list = malloc(sizeof(struct node));
int i=1,n,e;
scanf("%d",&n);
while(i <= n)
{
scanf("%d",&e);
insert(list,e);
i++;
}
show_sum(list);
return 0;
}
44
OUTPUT
3 320 320
100
115
105
4 200 200
50
53
47
50
5 11 11
1
2
3
3
2
3 37 37
10
15
12
RESULT
The program to print the total value of the linked list has been successfully executed
45
Ex.No.12 INSERT A NODE IN THE BEGINNING AND AT THE END OF THE LIST
DATE:04-06-2021
AIM
Write a program to insert a node in the beginning and at the end of the list
PROBLEM STATEMENT
Develop a menu driven program to insert a node in the linked list and display the same.
Based on the options given in the input, the corresponding subroutine should be executed.
The options are as follows-
option 1 - to insert a node in the beginning of the linked list
option 2 - to insert a node in the end of the linked list.
Input Format
no. of nodes n
next n lines denotes the values of the nodes
option
value of the node to insert
Sample Input
4
55
33
44
22
1
88
Sample Output
88
55
33
44
22
46
For example:
Input Result
4 88
55 55
33 33
44 44
22 22
1
88
3 3
3 4
4 5
5 6
2
6
ALGORITHM
Step 1 : Start.
Step 5 : Stop.
Step 1 : Start.
47
Step 5 : If List = NULL, then goto Step 6 else goto Step 7.
Step 1 : Start.
Step 8: Stop.
Step 1 : Start.
48
Step 5 : Set Position = Position→Next.
Step 9 : Stop.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int e;
struct node *next;
};
typedef struct node n;
void insert_e(n *list,int e)
{
n *temp = malloc(sizeof(n));
temp -> next = NULL;
temp -> e = e;
n *p;
p = list;
if(p -> next == NULL)
{
p -> next = temp;
}
else
{
while(p -> next != NULL)
{
p = p -> next;
}
p -> next = temp;
}
}
void insert_b(n *list,int e)
{
n *temp = malloc(sizeof(n));
temp -> next = NULL;
temp -> e = e;
n *p;
p = list;
if(p -> next == NULL)
{
49
p -> next = temp;
}
else
{
temp -> next = p -> next;
p -> next = temp;
}
}
void display(n *list)
{
n *p;
p = list;
while(p -> next != NULL)
{
p = p-> next;
printf("%d\n",p -> e);
}
}
int main()
{
int opt = 0,e,n,i=1,e1;
struct node *list = malloc(sizeof(n));
list -> next = NULL;
scanf("%d",&n);
while(i <= n)
{
scanf("%d",&e);
insert_e(list,e);
i++;
}
scanf("%d",&opt);
scanf("%d",&e1);
if(opt == 1)
{
insert_b(list,e1);
display(list);
}
if(opt == 2)
{
insert_e(list,e1);
display(list);
}
return 0;
}
50
OUTPUT
4 88 88
55 55 55
33 33 33
44 44 44
22 22 22
1
88
3 3 3
3 4 4
4 5 5
5 6 6
2
6
4 10 10
10 20 20
20 45 45
45 55 55
55 77 77
2
77
RESULT
The program to insert a node in the beginning and at the end of the list has been successfully
executed
51
Ex.No.13 MERGE TWO SINGLY LINKED LIST AND DISPLAY THE ELEMENTS
OF MERGED LIST
DATE:11-06-2021
AIM
Write a program to merge two singly linked list and display the elements of the merged list
PROBLEM STATEMENT
Write a C Program to Merge two Singly Linked List and Display the elements of Merged
List.
Input:
Number of Elements in List1 - m
m Elements in List1
Number of Elements in List2 - n
n Elements in List2
Output:
m+n Elements from List1 and List2
For example:
Input Result
3 10
10 20
20 30
30 40
3 50
40 60
50
60
ALGORITHM
Step 1: Start
Step 2:Declare and define a NODE structure with two members- element and struct node *next
Create pointer references to NODE- *position, *newnode, and *head1, *head2, *last1, *last2
initialised to NULL.
52
Step 3: Define a struct NODE pointer as node
Step 4: Declare and define a integer return type function- isempty with parameter node* head
to check if a list is empty.
Step 6: Declare and define a node pointer return type function- createnode with a integer
parameter a, to create a node
Step 9: Declare and define a void return type function- insertlast with parameters node* head,
int a, and int list to add a new element to alist
Step 11: if isempty(head) is not true, assign position with last of given head and position->next
by calling createnode(a), and if list is equal to 1, if it is list1 assign last1 with position- >next,
else assign last1 with position->next
Step 12: Else If list1 is equal to 1 assign head1 and last1 with createnode(a)
Step 14: Declare and define a integer return type function- display with parameter node* head
to print all the elements in a list
Step 16: Print position->element and increment position while position is not NULL
Step 20: For size loops, get num and insertlast() num to first list
53
Step 22: For size loops, get num and insertlast() num to first list
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node
{
int e;
struct node *next;
};
typedef struct node n;
void insert(n *list,int e);
void merge(n *list1,n *list2);
int main()
{
int i=1,no,c;
n *list1 = malloc(sizeof(n));
list1->next = NULL;
n *list2 = malloc(sizeof(n));
list2->next = NULL;
scanf("%d",&no);
while(i <= no){
scanf("%d",&c);
insert(list1,c);
i++;
}i=1;
scanf("%d",&no);
while(i <= no){
scanf("%d",&c);
insert(list2,c);
i++;
}i=1;
merge(list1,list2);
}
void insert(n *list,int e){
n *temp = malloc(sizeof(n));
n *p;
p = list;
temp->e = e;
temp->next = NULL;
if(list->next == NULL){
list->next = temp;
54
}
else{
while(p->next != NULL)
p = p->next;
p->next = temp;
}
}
void merge(n *list1,n *list2){
n *p1;
p1 = list1;
while(p1->next != NULL)
p1 = p1->next;
p1->next = list2->next;
p1 = list1;
while(p1->next != NULL){
p1 = p1->next;
printf("%d\n",p1->e);
}
}
OUTPUT
Input Expected Go
3 10 10
10 20 20
20 30 30
30 40 40
3 50 50
40 60 60
50
60
2 1 1
1 2 2
2 3 3
3 4 4
3 5 5
4
5
RESULT
The program to merge two singly linked list and display the elements of the merged list has
been successfully executed
55
Ex.No.14 COPY THE ELEMENTS OF ONE LIST TO ANOTHER LIST USING
LINKED LIST
DATE:11-06-2021
AIM
Write a program to copy elements of one list to another list using linked list
PROBLEM STATEMENT
Write a C Program to copy the elements of one List to another List using Linked List
Concept.
Input:
m - Elements in List1
m Elements of List1
Output:
m Elements of List2 copied from List1
For example:
Input Result
3 10
10 20
20 30
30
ALGORITHM
Step 1: Start
Step 2: Declare and define a NODE structure with two members- element and struct node *next
Step 3: Create pointer references to NODE- *position, *newnode, *temp and *head1, *head2,
*last1, *last2 initialised to NULL
Step 5: Declare and define a integer return type function- isempty with parameter node* head
56
to check if a list is empty a. If head is NULL, return 1, else return 0
Step 6: Declare and define a node pointer return type function- createnode with a integer
parameter a, to create a node
c. Return newnode
Step 7: Declare and define a void return type function- insertlast with parameters node* head,
int a, and
b. If isempty(head) is not true, assign position with last of given head and position-
>next by calling createnode(a), and if list is equal to 1, if it is list1 assign last1 with
position->next, else assign last1 with position->next
c. Else i. If list1 is equal to 1 assign head1 and last1 with createnode(a) ii. Else assign
head2 calling createnode(a)
Step 9: Declare and define a integer return type function- display with parameter node* head
to print all the elements in a list
b. Get size
c. For size loops, get num and insertlast() num to first list
e. Call insertlast() with temp->element and assign temp with temp->next while temp
57
f. is not NULL for list 2
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int e;
struct node *next;
};
typedef struct node n;
void insert(n *list,int e)
{
n *temp = malloc(sizeof(n));
n *p;
p = list;
temp -> e = e;
temp -> next = NULL;
if(list -> next == NULL)
list -> next = temp;
else
{
while(p -> next != NULL)
p = p-> next;
p -> next = temp;
}
}
void copy(n *list1,n *list2)
{
n *p;
p = list1;
while(p -> next != NULL)
{
p = p -> next;
insert(list2,p -> e);
}
}
void show(n *list2)
{
n *p;
p = list2;
while(p -> next != NULL)
{
p = p -> next;
58
printf("%d\n",p -> e);
}
}
int main()
{
int n,i=1,e;
struct node *list1 = malloc(sizeof(n));
list1 -> next = NULL;
struct node *list2 = malloc(sizeof(n));
list2 -> next = NULL;
scanf("%d",&n);
while(i <= n)
{
scanf("%d",&e);
h
i++;
}
copy(list1,list2);
show(list2);
}
OUTPUT
3 10 10
10 20 20
20 30 30
30
4 1 1
1 2 2
2 3 3
3 4 4
4
RESULT
The program to copy elements of one list to another list using linked list has been
successfully executed
59
Ex.No.15 SUM OF TWO POLYNOMIAL NUMBERS
DATE:11-06-2021
AIM
PROBLEM STATEMENT
Find the sum of two polynomial numbers. Represent the polynomial number using single
linked List
Input Format :
First line contains the degree of the 1st polynomial
Second line contains the Coefficient of 1st polynomial
Third line contains the degree of the 2nd polynomial
Fourth line contains the Coefficient of 2nd polynomial
Sample Input :
3
5201
2
431
Sample Output:
5x^3 + 6x^2 + 3x^1 + 2
Explanation:
5x^3 + 2x^2 + 1 + 4x^2 + 3x^1 + 1 = 5x^3 + 6x^2 + 3x^1 + 2
ALGORITHM
Step 2: Create a struct node containing co, pow and a self referencing pointer Next
60
c. Scan the co integer
e. Using an if else loop, check if list->next=NULL, if true then list ->next = NULL else
poly *pos= list
f. Implement a while loop for pos->next!=NULL and if true make pos = pos->next and
pos->next = new
d. Else if pos->co!=0 and pos->pow!=0 then print pos->co and pos->pow + and change
pos=pos->next
e. If t1 and t2 powers are equal then add the coefficients of t1 and t2 and assign them
61
to the result coefficient and change t1=t1->next and t2=t2->next
f. Else if t1->pow is greater than t2->pow then the result’s coefficient is t1->co and
result’s power is t1->pow and change t1=t1->next
g. Else if t2->pow is greater than t1->pow then the result’s coefficient is t2->co and
result’s power is t2->pow and change t2=t2->next
j. If t1 gives NULL but t2!= NULL then the result’s power and coefficient is the same
as that of t2 and change the value of t2 to t2->next and res->next=NULL
k. Else the result’s coefficient and power will be the same as that of t1 and change
t1=t1- >next and res->next=NULL
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int coeff;
int power;
struct node *next;
};
typedef struct node Poly;
int IsEmpty(Poly *poly)
{
62
if(poly->next == NULL)
return 1;
else
return 0;
}
void Insert(Poly *poly)
{
int power,a[100];
scanf("%d",&power);
for(int i=0;i<=power;i++)
scanf("%d",&a[i]);
int i = 0;
while(power >= 0)
{
Poly *Newnode = malloc(sizeof(Poly));
Newnode->power = power;
Newnode->coeff = a[i];
Newnode->next = NULL;
if(poly->next == NULL)
poly->next = Newnode;
else
{
Poly *Position;
Position = poly;
while(Position->next != NULL)
Position = Position->next;
Position->next = Newnode;
}
power--;
i++;
}
}
void Add(Poly *poly1 , Poly *poly2 ,Poly *poly3)
{
Poly *Position;
Poly *Newnode;
poly1 = poly1->next;
poly2 = poly2->next;
poly3->next = NULL;
Position = poly3;
while(poly1 != NULL && poly2 != NULL)
{
Newnode = malloc(sizeof(Poly));
if(poly1->power == poly2->power)
{
Newnode->power = poly1->power;
Newnode->coeff = poly1->coeff + poly2->coeff;
poly1 = poly1->next;
63
poly2 = poly2->next;
}
else if(poly1->power > poly2->power)
{
Newnode->power = poly1->power;
Newnode->coeff = poly1->coeff;
poly1 = poly1->next;
}
else if(poly1->power < poly2->power)
{
Newnode->power = poly2->power;
Newnode->coeff = poly2->coeff;
poly2 = poly2->next;
}
Newnode->next = NULL;
Position->next = Newnode;
Position = Newnode;
}
while(poly1 != NULL || poly2 != NULL)
{
Newnode = malloc(sizeof(Poly));
if(poly1 != NULL)
{
Newnode->power = poly1->power;
Newnode->coeff = poly1->coeff;
poly1 = poly1->next ;
}
if(poly2 != NULL)
{
Newnode->power = poly2->power;
Newnode->coeff = poly2->coeff;
poly2 = poly2->next ;
}
Newnode->next = NULL;
Position->next = Newnode;
Position = Newnode;
}
}
void Display(Poly *poly)
{
Poly *Position ;
Position = poly;
while(Position->next != NULL)
{
Position = Position->next;
if(Position->power != 0)
printf("%dx^%d+",Position->coeff,Position->power);
else
printf("%d",Position->coeff);
64
}
}
int main()
{
Poly *poly1 = malloc(sizeof(Poly));
Poly *poly2 = malloc(sizeof(Poly));
Poly *poly3 = malloc(sizeof(Poly));
poly1->next = NULL;
poly2->next = NULL;
Insert(poly1);
Insert(poly2);
Add(poly1,poly2,poly3);
Display(poly3);
return 0;
}
OUTPUT
3 5x^3+6x^2+3x^1+2 5x^3+6x^2+3x^1+2
5 2 0 1
2
4 3 1
2 5x^2+9x^1+7 5x^2+9x^1+7
5 4 2
1
5 5
RESULT
The program to perform sum of two polynomial numbers has been successfully executed
65
Ex.No.16 DIFFERENTIATION OF THE POLYNOMIAL EQUATION USING
SINGLY LINKED LIST
DATE:25-06-2021
AIM
Write a program to perform differentiation of the polynomial equation using singly linked list
PROBLEM STATEMENT
Find the differentiation of the polynomial equation using Singly Linked List.
Input Format :
First line contains the highest degree of the polynomial
Second line contains the Coefficient of polynomial
Sample Input :
5
3 0 -2 0 1 5
Sample Output:
15x^4 - 6x^2 + 1x^0
Explanation:
Differentiation (3x^5 + 0x^4 - 2x^3 + 0x^2 + 1x^1 + 5x^0) = 15x^4 - 6x^2 + 1x^0
ALGORITHM
Step 1: Start
Step 2: Declare and define a poly structure with three members- coeff,pow and struct node
*next .
a. Allocate memory for node and save location to newnode,. From the user get the
coefficient and power value
66
newnode,while choice=1.
b. While position is not equal to null and position->pow>=0 Print position->coff and
position->pow.
Step 6: In the function void differentiation, create a poly position and newnode
b. result->next=NULL
c. position=result
g. In the main function, create poly poly1 and result allocate the memory of poly,
declare poly1->next=null,from the user get the values of the polynomial, and create
poly 1 display poly 1 and result.
h. Stop.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int coeff;
int power;
struct node *next;
};
typedef struct node Poly;
int IsEmpty(Poly *poly)
{
if(poly->next == NULL)
67
return 1;
else
return 0;
}
void Insert(Poly *poly)
{
int p,a;
scanf("%d",&p);
while(p >= 0)
{
Poly *Newnode = malloc(sizeof(Poly));
Newnode->power = p;
scanf("%d",&a);
Newnode->coeff = a;
Newnode->next = NULL;
if(poly->next == NULL)
poly->next = Newnode;
else
{
Poly *Position;
Position = poly;
while(Position->next != NULL)
Position = Position->next;
Position->next = Newnode;
}
p--;
}
}
void Diff(Poly *poly1 , Poly *poly2)
{
Poly *Position;
Poly *Newnode;
poly1 = poly1->next;
poly2->next = NULL;
Position = poly2;
while(poly1 != NULL)
{
Newnode = malloc(sizeof(Poly));
Newnode->coeff = (poly1->coeff * poly1->power);
Newnode->power = poly1->power - 1;
poly1 = poly1->next;
Newnode->next = NULL;
Position->next = Newnode;
Position = Newnode;
}
}
68
void Display(Poly *poly)
{
Poly *Position ;
Position = poly->next;
while(Position != NULL && Position->power >= 0)
{
if(Position->coeff != 0)
printf("%dx^%d ",abs(Position->coeff),Position->power);
if(Position->next != NULL && Position->next->coeff > 0)
printf("+ ");
else if(Position->next != NULL && Position->next->coeff < 0)
printf("- ");
Position = Position->next;
}
}
int main()
{
Poly *poly1 = malloc(sizeof(Poly));
Poly *poly2 = malloc(sizeof(Poly));
poly1->next = NULL;
poly2->next = NULL;
Insert(poly1);
Diff(poly1,poly2);
Display(poly2);
return 0;
}
OUTPUT
RESULT
The program to perform differentiation of the polynomial equation using singly linked list
has been successfully executed
69
Ex.No.17 IMPLEMENTATION OF TREE TRAVERSAL
DATE:25-06-2021
AIM
PROBLEM STATEMENT
Devi is playing with her friends. She wants to teach different types of traversal in tree to
them. so help her to finish the task by implementing Traversals. Based on the user request the
program has to print the corresponding traversal for the tree. Use the Array to store the tree
elements. Empty node is represented by '-'
Input Format:
First Line : Traversal No
Second Line : Max nodes
Third Line : Tree datas to be stored in array in order
Sample Input :
1
16
-DAFEBRTGQ--V-JL
Sample Output:
GEQABDVRFJTL
ALGORITHM
Global:
Step 3: Declare two struct pointers left and right inside structure node.
main ()
STEP 1: Create node pointer “tree” and allocate memory for the pointer
70
STEP 2: Assign tree->left as NULL and tree-> right as NULL
STEP 5: Get the number of elements from the user and store it in variable ‘n’
STEP 7: Get the element for tree from user and store it in ‘e’
insert ()
71
STEP 6: Assign tree = new
STEP 7: Go to step 13
Inorder ()
Preorder ()
Postorder ()
72
PROGRAM
#include <stdio.h>
int right_value(char ch[100], int index, int max)
{
if(ch[index] != '-' && ((2*index) + 1) <= max)
return (2 * index) + 1;
return 0;
}
int left_value(char ch[100], int index,int max)
{
if(ch[index] != '-' && (2 * index) <= max)
return (2 * index) ;
return 0;
}
void preorder(char ch[100],int index,int max)
{
if(index>0 && ch[index]!='-')
{
printf("%c ",ch[index]);
preorder(ch,left_value(ch,index,max),max);
preorder(ch, right_value(ch,index,max),max);
}
}
void postorder(char ch[100],int index,int max)
{
if(index>0 && ch[index]!='-')
{
postorder(ch,left_value(ch,index,max),max);
postorder(ch,right_value(ch,index,max),max);
printf("%c ",ch[index]);
}
}
void inorder(char ch[100],int index,int max)
{
if(index>0 && ch[index] != '-')
{
inorder(ch,left_value(ch,index,max),max);
printf("%c ",ch[index]);
inorder(ch,right_value(ch,index,max),max);
}
}
int main()
{
int n,max;
char ch[100];
scanf("%d",&n);
scanf("%d",&max);
scanf("%s",ch);
73
switch(n)
{
case 1 :
inorder(ch,1,max-1);
break;
case 2 :
preorder(ch,1,max-1);
break;
case 3 :
postorder(ch,1,max-1);
break;
}
}
OUTPUT
1 G E Q A B D V R F J T L G E Q A B D V R F J T L
16
-DAFEBRTGQ--V-JL
2 A B D E C F G A B D E C F G
8
-ABCDEFG
3 Y Z X Y Z X
4
-XYZ
RESULT
74
Ex.No.18 IMPLEMENTATION OF BINARY SEARCH TREE
DATE:02-07-2021
AIM
PROBLEM STATEMENT
ALGORITHM
Step 2: Compare the search element with the value of root node in the tree.
Step 3: If both are matched, then display "Given node is found!!!" and terminate the function
Step 4: If both are not matched, then check whether search element is smaller or larger than
that node value.
Step 5: If search element is smaller, then continue the search process in left subtree.
Step 6: If search element is larger, then continue the search process in right subtree.
Step 7: Repeat the same until we find the exact element or until the search element is compared
with the leaf node
Step 8: If we reach to the node having the value equal to the search value then display "Element
75
is found" and terminate the function.
Step 9: If we reach to the leaf node and if it is also not matched with the search element, then
display "Element is not found" and terminate the function.
Step 1: Create a newNode with given value and set its left and right to NULL.
Step 4: If the tree is Not Empty, then check whether the value of newNode is smaller or larger
than the node (here it is root node).
Step 5: If newNode is smaller than or equal to the node then move to its left child. If newNode
is larger than the node then move to its right child.
Step 6: Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL).
Step 7: After reaching the leaf node, insert the newNode as left child if the newNode is smaller
or equal to that leaf node or else insert it as right child.
We use the following steps to delete a node with two children from BST...
Step 2: If it has two children, then find the largest node in its left subtree (OR) the smallest
node in its right subtree.
Step 3: Swap both deleting node and node which is found in the above step.
Step 4: Then check whether deleting node came to case 1 or case 2 or else goto step 2
Step 7: Repeat the same process until the node is deleted from the tree
PROGRAM
#include <stdio.h>
#include <stdlib.h>
76
typedef struct Node
{
int ele;
struct Node *left;
struct Node *right;
}node;
void Inorder(node *tree){
if (tree!=NULL){
Inorder(tree->left);
printf("%d ",tree->ele);
Inorder(tree->right);
}
}
node *insert(node *tree,int e){
if (tree==NULL){
node *New = (node*) malloc(sizeof(node));
New->ele=e;
New->left=NULL;
New->right=NULL;
tree=New;
}
else if (e<tree->ele){
tree->left = insert(tree->left,e);
}
else if (e>tree->ele){
tree->right = insert(tree->right,e);
}
return tree;
}
node *findmin(node *tree){
if (tree==NULL)
return NULL;
else if (tree->left==NULL)
return tree;
else
return findmin(tree->left);
}
node *findmax(node *tree){
if (tree==NULL)
return NULL;
else if (tree->right==NULL)
return tree;
else
return findmax(tree->right);
}
node *delete(node *tree, int e){
node *temp;
if (e<tree->ele){
tree->left = delete(tree->left,e);
77
}
else if (e>tree->ele){
tree->right = delete(tree->right,e);
}
else if (tree->left && tree->right){
temp = findmin(tree->right);
tree->ele=temp->ele;
tree->right=delete(tree->right, tree->ele);
}
else{
temp=tree;
if (tree->left == NULL)
tree=tree->right;
else if (tree->right == NULL)
tree=tree->left;
free(temp);
}
return tree;
}
int main(){
node *tree = (node*) malloc(sizeof(node));
tree->left=tree->right=NULL;
node *pos,*pos1;
int n,ch,i=1;
do{
scanf("%d",&ch);
switch (ch){
case 1:
scanf("%d",&n);
if (i==1){
tree=insert(tree->left,n);
pos=tree;
i++;
}
else
pos=insert(pos,n);
break;
case 2:
scanf("%d",&n);
tree=delete(tree,n);
break;
case 3:
pos1=findmin(tree);
printf("%d\n",pos1->ele);
break;
case 4:
pos1=findmax(tree);
printf("%d\n",pos1->ele);
break;
78
case 5:
Inorder(tree);
printf("\n");
break;
}
}while(ch!=6);
}
OUTPUT
1 15 15
20 40 40
1 15 30 35 40 15 30 35 40
30
1
40
1
35
1
15
3
4
2
20
5
6
RESULT
The program to implement binary search tree has been successfully executed
79
Ex.No.19 IMPLEMENTATION OF BINARY HEAP
DATE:02-07-2021
AIM
PROBLEM STATEMENT
ALGORITHM
Step 3: If newNode value is greater than its parent, then swap both of them.
Step 4: Repeat step 2 and step 3 until newNode value is less than its parent node (or) newNode
reaches to root.
Step 1: Swap the root node with last node in max heap
Step 3: Now, compare root value with its left child value.
Step 4: If root value is smaller than its left child, then compare left child with its right sibling.
Else goto Step 6
Step 5: If left child value is larger than its right sibling, then swap root with left child otherwise
80
swap root with its right child.
Step 6: If root value is larger than its left child, then compare root value with its right child
value.
Step 7: If root value is smaller than its right child, then swap root with right child otherwise
stop the process.
Step 8: Repeat the same until root node fixes at its exact position.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
typedef struct MinHeap MinHeap;
struct MinHeap {
int* arr;
int size;
int capacity;
};
int parent(int i) {
return (i - 1) / 2;
}
int left_child(int i) {
return (2*i + 1);
}
int right_child(int i) {
return (2*i + 2);
}
MinHeap* init_minheap(int capacity) {
MinHeap* minheap = (MinHeap*) calloc (1, sizeof(MinHeap));
minheap->arr = (int*) calloc (capacity, sizeof(int));
minheap->capacity = capacity;
minheap->size = 0;
return minheap;
}
MinHeap* insert_minheap(MinHeap* heap, int element) {
heap->size++;
heap->arr[heap->size - 1] = element;
int curr = heap->size - 1;
while (curr > 0 && heap->arr[parent(curr)] > heap->arr[curr]) {
int temp = heap->arr[parent(curr)];
heap->arr[parent(curr)] = heap->arr[curr];
heap->arr[curr] = temp;
curr = parent(curr);
}
return heap;
}
81
MinHeap* heapify(MinHeap* heap, int index)
{
if (heap->size <= 1)
return heap;
int left = left_child(index);
int right = right_child(index);
int smallest = index;
if (left < heap->size && heap->arr[left] < heap->arr[index])
smallest = left;
if (right < heap->size && heap->arr[right] < heap->arr[smallest])
smallest = right;
if (smallest != index)
{
int temp = heap->arr[index];
heap->arr[index] = heap->arr[smallest];
heap->arr[smallest] = temp;
heap = heapify(heap, smallest);
}
return heap;
}
MinHeap* delete_minimum(MinHeap* heap) {
if (!heap || heap->size == 0)
return heap;
int size = heap->size;
int last_element = heap->arr[size-1];
heap->arr[0] = last_element;
heap->size--;
size--;
heap = heapify(heap, 0);
return heap;
}
void print_heap(MinHeap* heap) {
for (int i=0; i<heap->size; i++) {
printf("%d ", heap->arr[i]);
}
printf("\n");
}
int main(){
MinHeap* heap = init_minheap(10);
int n,choice;
do{
scanf("%d",&choice);
switch (choice){
case 1:
scanf("%d",&n);
insert_minheap(heap, n);
break;
case 2:
82
delete_minimum(heap);
break;
case 3:
print_heap(heap);
break;
}
}while(choice!=4);
}
OUTPUT
1 20 5 15 20 30 25 5 15 20 30 25
1 30 15 25 20 30 15 25 20 30
1 5
1 15
1 25
3
2
3
4
RESULT
83
Ex.No.20 IMPLEMENTATION OF DEPTH FIRST SEARCH
DATE:09-07-2021
AIM
PROBLEM STATEMENT
Consider a Graph G Perform Depth First Traversal on the given graph. Vertices of the graph
goes like 1, 2, 3 ...... n.
Input :
n - Integer - number of vertices
nxn - adjacency matrix for the graph G
m - Integer - starting vertex
Output:
List of n vertices - DFS Order.
For example:
Input Result
4 2
0 1 0 1 1
1 0 1 0 4
0 1 0 0 3
1 0 0 0
2
ALGORITHM
Step 1: Start
Step 3: Select any vertex as starting point for traversal. Visit that vertex and push it on to the
Stack. Step 4: Visit any one of the non-visited adjacent vertices of a vertex which is at the top
of stack and push it on to the stack.
Step 5: Repeat step 3 until there is no new vertex to be visited from the vertex which is at the
84
top of the stack.
Step 6: When there is no new vertex to visit then use back tracking and pop one vertex from
the stack. Step 7: Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 8: When stack becomes Empty, then produce final spanning tree by removing unused
edges from the graph
Step 9: Stop
PROGRAM
#include<stdio.h>
#define size 10
int graph[10][10];
int visited[size];
void DFS(int node,int vertices)
{
printf("%d\n",node+1);
visited[node]=1;
for(int j=0;j<vertices;j++)
if(visited[j]!=1 && graph[node][j]==1)
DFS(j,vertices);
}
int main()
{
int i,j,vertices,start_node;
scanf("%d",&vertices);
for(i=0;i<vertices;i++){
visited[i]=0;
}
for(i=0;i<vertices;i++)
{
for(j=0;j<vertices;j++)
scanf("%d",&graph[i][j]);
}
scanf("%d",&start_node);
DFS(start_node-1,vertices);
}
85
OUTPUT
4 2 2
0 1 0 1 1 1
1 0 1 0 4 4
0 1 0 0 3 3
1 0 0 0
2
5 2 2
0 1 1 1 0 1 1
1 0 0 0 1 3 3
1 0 0 0 1 5 5
1 0 0 0 1 4 4
0 1 1 1 0
2
RESULT
86
Ex.No.21 IMPLEMENTATION OF BREADTH FIRST SEARCH
DATE:09-07-2021
AIM
PROBLEM STATEMENT
Consider a Graph G Perform Breadth First Traversal on the given graph. Vertices of the
graph goes like 1, 2, 3 ...... n.
Input :
n - Integer - number of vertices
nxn - adjacency matrix for the graph G
m - Integer - starting vertex
Output:
List of n vertices - BFS Order.
For example:
Input Result
4 2
0 1 0 1 1
1 0 1 0 3
0 1 0 0 4
1 0 0 0
2
ALGORITHM
Step 1: Start
Step 2: choose any node in the graph, designate it as the search node and mark it as visited.
Step 3: Using the adjacency matrix of the graph, find all the unvisited adjacent nodes to search
node and enqueue them into the queue Q.
Step 4: Then the node is dequeued from the queue. Mark that node as visited and designate it
as the new search node. S
87
Step 5:Repeat step 2 and 3 using the new search node
Step 6: This process continues until the queue Q which keeps track of the adjacent nodes
become empty
Step 7: Start
PROGRAM
#include<stdio.h>
#define size 10
int queue[size],visited[size],queuelist[size];
int front=-1,rear=-1;
int graph[10][10];
int isempty()
{
if(rear==-1 && front==-1)
return 1;
return 0;
}
void Enqueue(int a)
{
rear++;
queue[rear]=a;
if(front==-1)
front+=1;
}
int Dequeue()
{
int temp=queue[front];
if(front==rear)
front=rear=-1;
else
front+=1;
return temp;
}
OUTPUT
4 2 2
0 1 0 1 1 1
1 0 1 0 3 3
0 1 0 0 4 4
1 0 0 0
2
5 3 3
0 1 1 1 0 1 1
1 0 0 0 1 5 5
1 0 0 0 1 2 2
1 0 0 0 1 4 4
0 1 1 1 0
3
RESULT
The program to implement breadth first search has been successfully executed
89
Ex.No.22 IMPLEMENTATION OF TOPOLOGICAL SORT
DATE:16-07-2021
AIM
ALGORITHM
Step 1: Start
Step 3: Find a vertex U with indegree o and print it (store it in the ordering) If there is no such
vertex then there is a cycle and the vertices cannot be ordered. Stop.
Step 4: Remove U and all its edges (U,V) from the graph.
Step 7: Stop
PROGRAM
#include<stdio.h>
int m,n;
int a[100][100];
int front=-1,rear=-1;
int visited[100];
int queue[100];
int in_degree[100];
int t[100];
int g=0;
int isEmpty()
{
if(front == -1)
return 1;
else
return 0;
}
void Enqueue(int a)
{
queue[++rear] = a;
if(front == -1)
90
front = 0;
}
int Dequeue()
{
int m = queue[front];
if(front == rear)
front = rear = -1;
else
front = front + 1;
return m;
}
void topo()
{
int m;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j])
in_degree[j] = in_degree[j] + 1;
}
}
for(int i=0;i<n;i++)
{
if(!in_degree[i])
{
Enqueue(i+1);
visited[i+1] = 1;
}
}
while(!isEmpty())
{
m = Dequeue();
t[g++] = m;
for(int j=0;j<n;j++)
{
if(a[m-1][j] && !(visited[j+1]))
{
--in_degree[j];
if(!in_degree[j])
{
Enqueue(j+1);
visited[j+1] = 1;
}
}
}
}
}
int main()
91
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
topo();
for(int i=0;i<n;i++)
printf("%d ",t[i]);
return 0;
}
OUTPUT
87 56 12 45 9
9 12 45 56 87
RESULT
92
Ex.No.23 IMPLEMENTATION OF MERGE SORT
DATE:16-07-2021
AIM
ALGORITHM
Step 1: Start
Step 8: Stop
PROGRAM
#include <stdio.h>
#include <stdlib.h>
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int sub1[n1], sub2[n2];
for (i = 0; i < n1; i++)
sub1[i] = a[beg + i];
for (j = 0; j < n2; j++)
sub2[j] = a[mid + 1 + j];
i = 0;
j = 0;
k = beg;
while (i < n1 && j < n2) {
if (sub1[i] <= sub2[j]) {
a[k] = sub1[i];
i++;
}
93
else
{
a[k] = sub2[j];
j++;
}
k++;
}
while (i < n1) {
a[k] = sub1[i];
i++;
k++;
}
while (j < n2) {
a[k] = sub2[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end) {
int mid = beg + (end - beg) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
void printArray(int a[], int size)
{
for (int i = 0; i < size; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int size,a[100];
printf("\nEnter the size of the array : ");
scanf("%d",&size);
printf("\nEnter the array elements :\n");
for(int i=0;i<size;i++)
scanf("%d",&a[i]);
mergeSort(a, 0, size - 1);
printf("\nSorted array is \n");
printArray(a, size);
return 0;
}
94
OUTPUT
76
12
43
98
Sorted array is
8 12 43 76 98
RESULT
95
Ex.No.24 IMPLEMENTATION OF QUICK SORT
DATE:23-07-2021
AIM
ALGORITHM
Step 4: Since 2< 5, shift left pointer right Since 65, stop
Step 9: Stop
PROGRAM
#include<stdio.h>
void quicksort(int a[10],int beg,int end)
{
int pivot,i,j,temp;
if(beg < end)
{
pivot = beg;
i = beg;
j = end;
while(i < j)
{
while(a[i] <= a[pivot] && i < end)
i++;
while(a[j] > a[pivot])
j--;
if(i < j)
{
96
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[pivot];
a[pivot] = a[j];
a[j] = temp;
quicksort(a,beg,j-1);
quicksort(a,j+1,end);
}
}
int main()
{
int a[10],n;
printf("\nEnter the size of the array : ");
scanf("%d",&n);
printf("\nEnter the array elements :\n");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("\nSorted array :\n");
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
OUTPUT
34
23
22
45
56
Sorted array :
22 23 34 45 56
97
RESULT
98
Ex.No.25 IMPLEMENTATION OF HASHING
DATE:23-07-2021
AIM
ALGORITHM
Step 1: Start
Step 4: If choice is 1, perform insertion(), else if choice is 2, perform del(), else if choice is 3,
perform search(), else if choice is 4, perform print()
Step 5: Stop
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *chain[100];
void init(int size)
{
int i;
for(i = 0; i < size; i++)
chain[i] = NULL;
}
void insert(int num, int size)
{
struct node *newnode = malloc(sizeof(struct node));
newnode->data = num;
newnode->next = NULL;
if(chain[key] == NULL)
chain[key] = newnode;
99
else
{
struct node *temp = chain[key];
while(temp->next)
{
temp = temp->next;
}
temp->next = newnode;
}
}
void display(int size)
{
for(int i = 0; i < size; i++)
{
struct node *temp = chain[i];
printf("chain %d ==> ",i);
while(temp)
{
printf("%d ==> ",temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}
int main()
{
int size,n;
printf("\nEnter the number of elements to be inserted : ");
scanf("%d",&size);
init(size);
for(int i=0;i<size;i++)
{
printf("\nEnter the element : ");
scanf("%d",&n);
insert(n,size);
}
display(size);
return 0;
}
OUTPUT
100
Enter the element : 23
RESULT
101