0% found this document useful (0 votes)
557 views105 pages

Rajalakshmi: Cs19241-Data Structuress

The document contains a laboratory note book for the subject "Data Structures" belonging to a student. It includes details like the student's name, register number, semester, academic year, bonafide certificate and index of programs completed along with their output. The programs cover topics like reversing a string using stack, balancing parentheses using stack, converting infix to postfix notation using stack and other data structures concepts.

Uploaded by

AHAMED N - 04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
557 views105 pages

Rajalakshmi: Cs19241-Data Structuress

The document contains a laboratory note book for the subject "Data Structures" belonging to a student. It includes details like the student's name, register number, semester, academic year, bonafide certificate and index of programs completed along with their output. The programs cover topics like reversing a string using stack, balancing parentheses using stack, converting infix to postfix notation using stack and other data structures concepts.

Uploaded by

AHAMED N - 04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

RAJALAKSHMI ENGINEERING COLLEGE

RAJALAKSHMI NAGAR, THANDALAM-602 105

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.. *****************

College RollIN 0 150LDL3 *** *********

Semester L.
Academic Ycar
RAJALAKSHMI
ENGINEERING COLLEGE
Ad a UNV .

BONAFIDE CERTIFICATE

MAME- Harii Mlnugan


NCADEIC VEAR 2020-2021sEMESTE. N H l &ML

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

Signature of raculty- in - Charge

Submitted for the Practical Examination held on

tnternal Examiner External Examiner


RAJALAKSHMI
ENGINEERING COLLEGE
Arntiated t o ANNA UNIVERSITY, Chennai

CS19241-DATA STRUCTURES LABORATORY

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

.25.202 Toprint the i s t tile in the printer queue

285 2021 Print the count of same value in two Linked

List.
285.2021 Sort the aay in incrcasing order and print out
the original indes position of the new sorted Lb

0 pietmemlalion of Circular Linked List. 30


10.4.6.2021
4202 Pint the toal value of Linked LAst.
12 4.6.2021 Isert a node in
the beginning and at the end of
the list.
13 1.62021 Merge two Singly Linkad List and Display the

elements of Merged Lst.

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

Write a program to reverse a string using stack

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.

Constraint: String can be of size 10.


Input: Input string S
Output: Reverse of a string given as input or overflow if string is above size 10.
Test Case 1:
Input:
madam
Output
Madam

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

int push(char ch)


{
if(isFull())
{
printf("Overflow");
exit(0);
}
else
{
stack[++top] = ch;
}
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

Input Expected Got

Madam madam madaM

Hello olleH olleH

ABCDEFGHIJKL Overflow Overf


low

ABCDEFMHIJKL Overflow Overf


low

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

Write a program to balance paranthesis using stack

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

“(()))” Not Balanced

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

Input Expected Got

“((()))” Balanced Balanced

“(()))” Not Balanced Not Balanced

“()” Balanced Balanced

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

Write a program to convert infix to postfix using stack

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.

Step 9: Print the output


Step 10: Pop and output from the stack until it is not empty
Step 11: Stop

PROGRAM

#include<stdio.h>
#include<string.h>

#define MAX 20
int Stack[MAX], top = -1;
char expr[MAX], post[MAX];

void Push(char sym);


char Pop();
char Top();
int Priority(char sym);

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

void Push(char sym)


{
top = top + 1;
Stack[top] = sym;
}

char Pop()
{
char e;
e = Stack[top];
top = top - 1;
return e;
}

char Top()
{
return Stack[top];
}

int Priority(char sym)


{
int p = 0;
switch(sym)
{
case '(':
p = 0;
break;
case '+':
case '-':
p = 1;
break;
case '*':
case '/':
case '%':
p = 2;
break;
case '^':
p = 3;
break;
}
return p;

9
}

OUTPUT

Input Expected Got

a+b*c abc*+ abc*+

a*b+(c-d/e) ab*cde/-+ ab*cde/-+

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

Write a program to evaluate a postfix expression

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

Input Expected Got

abc+*d* 70 70
2
3
4
5

ab*cde/-+ 21 21
4
5
5
8
2

RESULT

The program to evaluate a postfix expression has been successfully executed

14
Ex.No.5 TO PICK UP THE LAST JOB IN THE QUEUE
DATE:21-05-2021

AIM

Write a program to pick up the last job in the queue

PROBLEM STATEMENT

Computer handles multiuser, multiprogramming environment and time-sharing environment.


In this environment a system (computer) handles several jobs at a time; to handle these jobs
the concept of a queue is used. Write a program to pick up the last job in the queue of a multi-
tasking environment.
Input: queue size n and list of jobs
Output: name of the last job

For example:
Input Result

4 close
Open open close close

ALGORITHM

Step 1: Start

Step 2: Initialize r = -1, f = -1 as a global variable

Step 3: Initialize q[30][30] as a global variable and a character. main()

Step 4: Int n

Step 5: Char c

Step 6:Read n

Step 7: Int i=0; i enq(char a)

Step 8: r++

Step 9: strcpy(q[r], a) deq()

15
Step 10: Display q[r]

Step 11: Stop

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

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

for(int i=0;i<size;i++)
{
scanf("%s",input_v);
enqueue(input_v);
}

16
printf("%s",queue[rear]);

return 0;
}

OUTPUT

Input Expected Got

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

Write a program to print the first file in the printer queue

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 2: Assign and initialize f as -1, r as -1 and d as 0

Step 3: Declare a two-dimensional array queue

Step 4: Declare and define a void return type function – push with parameters int n and char
a[], to add element to the queue

a. If r is equal to n-1, Display Overflow, Assign d as 1

b. Else, if f is equal to -1, increment f by 1

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++]

Step 6: In main() function

a. Declare two integers n, m and two character arrays a[] and b[]

b. Input two integers and assign to n and m

c. Input a string and assign to a

d. Declare and initialized x as 0

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

f. Assign b[x] as ‘\0’

g. Call push(n,b)

h. If d is equal to 0, Display Call pop(n) i. Return 0

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

Input Expected Got

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 2: Read an integer as n.

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

Step 5: Call the check function

Step 6 CHECK FUNCTION:

a. STEP 1: Assign same=0

b. STEP 2: Assign x to each element of the 1st list

c. STEP 3: Check whether x is equal to any of the elements of the 2nd list.

d. If yes, go to STEP 4 else STEP 5

e. STEP 4: Increment same

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

Input Expected Got

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

Step 2: SORT FUNCTION:

a. Declare an array arr of size n and copy the list elements to the

b. array arr

c. Sort the array arr

d. Run a for loop

e. Assign x to each element of the array arr

f. Check whether x is equal to any of the elements of the list.

g. If yes go to STEP 5 else STEP 6

h. Print the index position of that element in the list

i. Continue with the next element of the array until it reaches the end.

Step 3: In the main function():

a. Start

27
b. Read the number of elements as n

c. Read each element of the array and insert it to the list

d. Call Sort function

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

void insert(int *a,int n)


{
for(int i=0;i<n;i++)
scanf("%d",(a+i));
}
void copy(int *a,int *b,int n)
{
for(int i=0;i<n;i++)
*(b+i) = *(a+i);
}
void index_value(int *a, int *b, int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(*(b+i) == *(a+j))
{
printf("%d ",j);
}
}
}
28
}
int main()
{
int a[100000],b[100000],n;

scanf("%d",&n);

insert(a,n);
copy(a,b,n);
sort(b,n);
index_value(a,b,n);

return 0;
}

OUTPUT

Input Expected Got

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

Write a program to implement circular linked list

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.

Step 3: Create a function isempty with int return type

• Check if list->next is list then return 1 else return 0.

Step 4: Create a function Traverse with void return type

• Check if isempty(list) print empty and return.

• Create new Node pos and assign it to list->next.

30
• Until pos->next is not list print the element and change pos as pos->next.

• Print the last element.

Step 5: Create a function findprevious with return type as Node *

• Create a new Node pos and assign it to list.

• Until pos->next is not list and pos->next->element is not e change pos as pos->next.

• Return Node pos.

Step 6: Create a function Insert with return type as void

• Create a new Node NewNode and assign NewNode->element as e and NewNode-


>next as list.

• Check if isempty() then list->next=NewNode;

• Else assign list to a new Node position Change position as position->next until
position->next is not list.

• Set position->next as NewNode.

Step 7: Create a function Delete with return type void

• Check if isempty() then print cannot delete and return.

• Call findprevious() and assign it to position

• Create TempNode and assign it to position->next.

• Set position->next as TempNode->next and free TempNode.

Step 8: Create a function Length with return type void

• If list->next is list then print 0.

• Else

a. Initialize a variable tot as 0.

b. Create a Node Position and set it to list.

c. Until Position->next is not list increment tot by 1 and set Position as Position-

31
>next d. Print tot.

Step 9: In the main() function

• Create a new Node list and assign list->next as list.

• Declare variables choice and e.

• Until the entered choice is not 5

a. Input the choice

a. If choice is 1 input element and call Insert().

b. If choice is 2 input element and call Delete().

c. If choice is 3 call Traverse().

d. If choice is 4 call Length().

Step 10: Stop

PROGRAM

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int element;
struct node * next;
}Node;

int isempty(Node * list) { if(list->next==list)


return 1;
else
return 0;
}
void Traverse(Node* list) { if(isempty(list)) {
printf("Linked list is empty"); return;
32
}
Node* pos=list->next; while (pos->next!=list) {
printf("%d ",pos->element); pos=pos->next;
}
printf("%d\n",pos->element);
}
Node * findprevious(Node * list,int e) { Node * pos;
pos=list;
while(pos->next!=list &&
pos->next->element!=e) pos=pos->next;
return pos;
}
void Insert(Node * list,int e) { Node *
NewNode=(Node*)malloc(sizeof(Node));
NewNode->element=e;
NewNode->next=list;
if(isempty(list))
list->next=NewNode;
else
{
Node * position=(Node*)malloc(sizeof(Node)); position=list;
while(position->next!=list) position=position->next;
position->next=NewNode;
}
}
void Delete(Node * list,int e) { if(isempty(list)) {
printf("Can't delete "); return;
}
Node * TempNode, * position; position=findprevious(list,e); TempNode=position->next;
position->next=TempNode->next; free(TempNode);
}
33
void Length(Node * list) { if(list->next==list)
printf("0");
else {
int tot=0;
Node * Position =list; while(Position->next!=list) {
tot++;
Position=Position->next;
}
printf("%d\n", tot);
}
}
int main() {
Node * list=(Node*)malloc(sizeof(Node)); list->next=list;
int choice ,e; do{
scanf("%d",&choice); switch(choice)
{
case 1:
scanf("%d",&e); Insert(list,e); break;
case 2:
scanf("%d",&e); Delete(list,e); break;
case 3:
Traverse(list); break;
case 4:
Length(list); break;
}
} while(choice!=5); return 0;
}

34
OUTPUT

Input Expected Got

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

Write a program to print the list in reverse

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

Algorithm for insert(Node *list)

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 4: Execute Node *NewNode = malloc(sizeof(Node)),where required amount of bytes will


be allocated for NewNode.

Step 5: Input element for the NewNode.

Step 6:If next position of list is NULL,goto step 7,else goto step 8.

Step 7: Save next position of NewNode as NULL.

Step 8: Save next of list to the next of NewNode.

Step 9: Save next position of list as NewNode.

Step 10: STOP.

Algorithm for traverse(Node *list)

Step 1: START.

Step 2: Initialise position under node.

Step 3: In position save next position of list.

37
Step 4: Execute while loop until next of position is null,goto step 5.

Step 5: Display the element in the position,goto step 9.

Step 6: Set position as next of position.

Step 7: Display the element in the position,goto step 9..

Step 8: Display list is empty.

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

Input Expected Got

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

Write a program to print the total value of the linked list

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

Algorithm for insert(Node *list)

Step 1 : Start.

Step 2 : Set NewNode = addressof(Node).

Step 3 : Input element for the newnode.

Step 4 : If List = NULL, then goto Step 5 else goto Step 6.

Step 5 : Set NewNode→Next = NULL and goto Step 7.

Step 6 : Set NewNode→Next = List→Next.

Step 7 : Set List→Next = NewNode.

Step 8: Stop.

Algorithm for display(Node *list)

Step 1: Initialise sum = 0.

Step 2: Initialise position.

Step 3: Next node of position will be saved in position.

Step 4: Execute while loop,where it runs until the next of position reaches NULL,if true goto
step 5,else goto

Step 5: Execute sum+=position->element,position=position->next.

Step 6: Execute sum+=position->element.

Step 7: Display sum.

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

Input Expected Got

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

Algorithm for IsEmpty(Node *List)

Step 1 : Start.

Step 2 : If List→Next = NULL goto

Step 3 else goto Step 4.

Step 3 : Return 1 and Stop.

Step 4 : Return 0 and Stop.

Step 5 : Stop.

Algorithm for InsertLast(Node *List, int e)

Step 1 : Start.

Step 2 : Set NewNode = addressof(Node).

Step 3 : Set NewNode→Element = e.

Step 4 : Set NewNode→Next = NULL.

47
Step 5 : If List = NULL, then goto Step 6 else goto Step 7.

Step 6 : Set List→Next = NewNode and goto Step 11.

Step 7 : Set Position = List.

Step 8 : Repeat the Step 9 until Position→Next != NULL.

Step 9 : Set Position = Position→Next.

Step 10: Set Position→Next = NewNode.

Step 11: Stop.

Algorithm for InsertBeg(Node *List, int e)

Step 1 : Start.

Step 2 : Set NewNode = addressof(Node).

Step 3 : Set NewNode→Element = e.

Step 4 : If List = NULL, then goto Step 5 else goto Step 6.

Step 5 : Set NewNode→Next = NULL and goto Step 7.

Step 6 : Set NewNode→Next = List→Next.

Step 7 : Set List→Next = NewNode.

Step 8: Stop.

Algorithm for Traverse(Node *List)

Step 1 : Start.

Step 2 : If !IsEmpty = TRUE goto Step 3 else goto Step 8.

Step 3 : Set Position = List.

Step 4 : Repeat the Steps 5-6 until Position→Next != NULL.

48
Step 5 : Set Position = Position→Next.

Step 6 : Display Position→Element.

Step 7 : Goto Step 9.

Step 8 : Display “List is empty”.

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

Input Expected Got

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 5: 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

Step 7: Allocate memory for node and save location tonewnode

Step 8: Assign newnode->next to NULL and newnode->next toa Return newnode

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 10: Assign position with head

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 13: Else assign head2 calling 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 15: Assign position with head

Step 16: Print position->element and increment position while position is not NULL

Step 17: In the main() function

Step 18: Declare integer variables size and num

Step 19: Get size

Step 20: For size loops, get num and insertlast() num to first list

Step 21: Get siz

53
Step 22: For size loops, get num and insertlast() num to first list

Step 23: Assign last1->next to head2

Step 24: Call display() with head1

Step 25: End

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 4: Define a struct NODE pointer as node

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

a. Allocate memory for node and save location tonewnode

b. Assign newnode->next to NULL and newnode->next toa

c. Return newnode

Step 7: Declare and define a void return type function- insertlast with parameters node* head,
int a, and

Step 8: int list to add a new element to alist

a. Assign position with head

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

a. Assign position with head

b. Print position->element and increment position while position is not NULL

Step 10: In the main() function

a. Declare integer variables size and num

b. Get size

c. For size loops, get num and insertlast() num to first list

d. Assign temp with head1

e. Call insertlast() with temp->element and assign temp with temp->next while temp

57
f. is not NULL for list 2

g.Call display() with head2

Step 11: End

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

Input Expected Got

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

Write a program to perform sum of polynomial numbers

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 1: Start the program

Step 2: Create a struct node containing co, pow and a self referencing pointer Next

Step 3: Create a function “create” with a return type void

a. Create a do while loop

b. Define a new poly pointer and allocate memory

60
c. Scan the co integer

d. Assign new->co = co and new->pow=pow and new->next=NULL

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

g. Decrement power variable pow

Step 4: Create a function Display with a return type void

a. Define poly* pos = list->next

b. While pos->next!=NULL start an if else if loop

c. If pos->next->coco and pos->pow and change pos=pos->next

d. Else if pos->co!=0 and pos->pow!=0 then print pos->co and pos->pow + and change
pos=pos->next

e. Else if pos->co is equal to 0 then change pos=pos->next

f. Else print pos->co+ and change pos=pos->next

g. If pos->co!=0 and pos->pow!=0 then print pos->co x^ pos->pow and change


pos=pos- >next h. Else if pos->co==0 change pos=pos->next

i. Else print pos->co and change pos=pos->next

Step 5: Create a function Addition with a return type void

a. Assign poly* t1 to list1->next

b. Assign poly* t2 to list2->next

c. While t1 and t2 is not equal to 0 goto next step

d. Allocate memory for poly *res

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

h. If res->next=NULL then result->next=res else poly *pos=resulti

i. While pos->next!=NULL then change pos->next=res

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

Step 6: In the main function:

a. Allocate memory for t1, t2 and res pointers

b. Scan the values for powers for t1 and t2

c. Call create function

d. Call the addition function

e. Call the display function

Step 7: Stop the program

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

Input Expected Got

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 .

Step 3: Define a struct poly pointer as poly.

Step 4:Declare and define a poly pointer function- create.

a. Allocate memory for node and save location to newnode,. From the user get the
coefficient and power value

b. Assign newnode->next to NULL and POSITION->next to newnode ,position=

66
newnode,while choice=1.

Step 5: In the function display, create a poly position.

a. Declare position= list->next.

b. While position is not equal to null and position->pow>=0 Print position->coff and
position->pow.

c. If position!=null and position->coeff>0 Print +

Step 6: In the function void differentiation, create a poly position and newnode

a. Declare poly1= poly1->next.

b. result->next=NULL

c. position=result

d. While poly is not NULL, allocate the memory of poly to newnode

e. Declare newnode->coeff= poly1->coff*poly1->pow.

f. newnode-.pow==poly1->pow-1 . poly1=poly1->next, newnode->next=null,position-


>next=newnode, position= newnode

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

Input Expected Got

3 15x^2 + 8x^1 + 2x^0 15x^2 + 8x^1 + 2x^0


5 4 2 7

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

Write a program to implement tree traversal

PROBLEM STATEMENT

1. Inorder 2. Preorder 3. Postorder

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 1: Declare a structure named “node”

Step 2: Declare an integer element inside structure node

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 3: Declare node pointer ‘pos’ and set, pos = tree

STEP 4: Declare integer variables i, n, e

STEP 5: Get the number of elements from the user and store it in variable ‘n’

STEP 6: Check if i< n, if true go to step 7, else go to step 14

STEP 7: Get the element for tree from user and store it in ‘e’

STEP 8: If i==0, then go to step 9, else go to step 11

STEP 9: Assign tree = insert(tree->left, n)

STEP 10: Assign pos = tree, go to step 12

STEP 11: Assign pos = insert (pos, e)

STEP 12: Increment i

STEP 13: Go to step 6

STEP 14: Exit loop

STEP 15: Call function preorder(tree)

STEP 16: Call function inorder(tree)

STEP 17: Call function postorder(tree)

STEP 18: END

insert ()

STEP 1: Check if tree==NULL, if true go to step 2, else go to step 8

STEP 2: Declare a node “new” and allocate memory for it

STEP 3: Assign new->ele = e

STEP 4: Assign new->left as NULL

STEP 5: Assign new->right as NULL

71
STEP 6: Assign tree = new

STEP 7: Go to step 13

STEP 8: Check if e < tree->ele, if true go to step 9, else go to step 11

STEP 9: Assign tree->left = insert(tree->left, e)

STEP 10: Go to step 13

STEP 11: Check if e> tree->ele, if true go to step 12

STEP 12: Assign tree->right = insert(tree->right, e)

STEP 13: Return tree

Inorder ()

STEP 1: Check if tree! =NULL, if true go to step 2

STEP 2: Recursively call inorder (tree->left)

STEP 3: Display tree->ele

STEP 4: Recursively call inorder (tree->right)

Preorder ()

STEP 1: Check if tree! =NULL, if true go to step 2

STEP 2: Display tree->ele

STEP 3: Recursively call inorder (tree->left)

STEP 4: Recursively call inorder (tree->right)

Postorder ()

STEP 1: Check if tree! =NULL, if true go to step 2

STEP 2: Recursively call inorder (tree->left)

STEP 3: Recursively call inorder (tree->right)

STEP 4: Display tree->ele

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

Input Expected Got

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

The program to implement tree traversal has been successfully executed

74
Ex.No.18 IMPLEMENTATION OF BINARY SEARCH TREE
DATE:02-07-2021

AIM

Write a program to implement binary search tree

PROBLEM STATEMENT

Implement Binary Search Tree with following option


1 - Insertion
2 - Deletion
3 - Find Min
4 - Find Max
5 - Inorder Display
6 - exit

ALGORITHM

The search operation is performed as follows...

Step 1: Read the search element from the user.

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.

The insertion operation is performed as follows...

Step 1: Create a newNode with given value and set its left and right to NULL.

Step 2: Check whether tree is Empty.

Step 3: If the tree is Empty, then set root to newNode.

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 1: Find the node to be deleted using search operation

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 5: If it comes to case 1, then delete using case 1 logic.

Step 6: If it comes to case 2, then delete using case 2 logic.

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

Input Expected Got

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

Write a program to implement binary heap

PROBLEM STATEMENT

Implement the Binary Min heap with the following options


1 - Insert
2 - Delete Min
3 - Display
4 - exit

ALGORITHM

Insertion Operation in max heap is performed as follows...

Step 1: Insert the newNode as last leaf from left to right.

Step 2: Compare newNode value with its Parent node.

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.

following steps to delete the root node from a max heap...

Step 1: Swap the root node with last node in max heap

Step 2: Delete last node.

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

Input Expected Got

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

The program to implement binary heap has been successfully executed

83
Ex.No.20 IMPLEMENTATION OF DEPTH FIRST SEARCH
DATE:09-07-2021

AIM

Write a program to implement depth first search

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 2: Define a Stack of size total number of vertices in the graph.

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

Input Expected Got

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

The program to implement depth first search

86
Ex.No.21 IMPLEMENTATION OF BREADTH FIRST SEARCH
DATE:09-07-2021

AIM

Write a program to implement breadth first search

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

void BFS (int node,int vertices)


{
printf("%d\n",node+1);
visited[node]=1;
for(int j=0;j<vertices;j++)
{
if((graph[node][j]==1 && visited[j]!=1) && queuelist[j]!=1)
{
Enqueue(j);
queuelist[j]=1;
}
88
}
if(!isempty())
BFS(Dequeue(),vertices);
}
int main()
{
int i,j,vertices,start_node;
scanf("%d",&vertices);
for(i=0;i<vertices;i++)
{
visited[i]=0;
queuelist[i]=0;
}
for(i=0;i<vertices;i++)
{
for(j=0;j<vertices;j++)
scanf("%d",&graph[i][j]);
}
scanf("%d",&start_node);
BFS(start_node-1,vertices);
}

OUTPUT

Input Expected Got

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

Write a program to implement topological sort

ALGORITHM

Step 1: Start

Step 2: Compute the indegrees of all vertices

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 5: Update the indegrees of the remaining vertices.

Step 6: Repeat steps 2 through 4 while there are vertices to be processed

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

The program to implement topological sort has been successfully executed

92
Ex.No.23 IMPLEMENTATION OF MERGE SORT
DATE:16-07-2021

AIM

Write a program to implement merge sort

ALGORITHM

Step 1: Start

Step 2: Divide the array into two parts

Step 3: Divide the array into two parts again

Step 4: Break each element into single parts

Step 5: Sort the elements from smallest to largest

Step 6: Merge the divided sorted arrays together

Step 7: The array has been sorted

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

Enter the size of the array : 5

Enter the array elements :

76

12

43

98

Sorted array is

8 12 43 76 98

RESULT

The program to implement merge sort has been successfully executed

95
Ex.No.24 IMPLEMENTATION OF QUICK SORT
DATE:23-07-2021

AIM

Write a program to implement quick sort

ALGORITHM

Step 1: Determine pivot

Step 2: Start pointers at left and right

Step 3: Since 4 < 5, shift left pointer

Step 4: Since 2< 5, shift left pointer right Since 65, stop

Step 5: since 9>5, shift right pointers since 35, stop

Step 6: Swap values at pointers

Step 7: Move pointers one more step

Step 8: since 5==5 move pointers one more step

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

Enter the size of the array : 5

Enter the array elements :

34

23

22

45

56

Sorted array :

22 23 34 45 56

97
RESULT

The program to implement quick sort has been successfully executed

98
Ex.No.25 IMPLEMENTATION OF HASHING
DATE:23-07-2021

AIM

Write a program to implement hashing

ALGORITHM

Step 1: Start

Step 2: Initialize 1 d array ‘arr’ with ‘size’ using init()

Step 3: Get choice from user

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;

int key = num % size;

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

Enter the number of elements to be inserted : 5

Enter the element : 23

Enter the element : 34

100
Enter the element : 23

Enter the element : 11

Enter the element : 56

chain 0 ==> NULL

chain 1 ==> 11==>56 ==>NULL

chain 2 ==> NULL

chain 3 ==> 23 ==> 23 ==>NULL

chain 4 ==> NULL

RESULT

The program to implement hashing has been successfully executed

101

You might also like