You are on page 1of 128

(AN ISO 9001-2008 CERTIFIED INSTITUTION)

(Approved by AICTE, New Delhi & Affiliated to Anna University)

No.60, Avadi – Vel Tech Road, Chennai-600 062.

CS 8381–DATA STRUCTURES LABORATORY

NAME : G. PREETHI

REGISTER NO : 113019104068

ROLL NO : VH-10050

BRANCH : B.E-Computer Science and Engineering

YEAR : II

SEMESTER : III
(AN ISO 9001-2008 CERTIFIED INSTITUTION)
(Approved by AICTE, New Delhi & Affiliated to Anna University)
No.60, Avadi – Vel Tech Road, Chennai-600 062.

BONAFIDE CERTIFICATE

Name : G.PREETHI .

Year: II Semester: III Branch: B.E – Computer Science and Engineering

University Register No: 113019104068 College Roll No: VH: 10050

Certified that this is the bonafide record of work done by the above student in the
CS 8381 – DATA STRUCTURES LABORATORY during the academic year 2020-21.

Signature of Head of the Department Signature of Course Incharge

Submitted for the University Practical Examination held on ………………... at VEL TECH HIGH
TECH Dr. RANGARAJAN Dr. SAKUNTHALA ENGINEERING COLLEGE, No.60, AVADI –
VEL TECH ROAD, AVADI, CHENNAI-600062.

Signature of Examiners

Internal Examiner:…………………… External Examiner:………………..……

Date:…………….……..
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA

ENGINEERING COLLEGE

INSTITUTION VISION

Pursuit of excellence in technical education to create civic responsibility with competency.

INSTITUTION MISSION

1. To impart the attributes of global engineers to face industrial challenges with social relevance.
2. To indoctrinate as front runners through moral practices.
3. To attain the skills through lifelong learning.
DEPARTMENT VISION

To blend academic learning process and innovative ideas producing self-confident graduates with
skills and knowledge to compete in the changing world.

DEPARTMENT MISSION

M1: To provide strong basic knowledge in Computer Science and Engineering.

M2: To motivate the students to function as a team from their innovative ideas in collaboration
with the industries.

M3: To enable the students to lead and adapt to the growing environment.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO 1:
Embark upon successful professional practice in Computer Science and Engineering,
displaying supportive and leadership roles.
PEO 2:
Engage in professional projects requiring teamwork and making valuable contributions to
design, development, and production in the practice of Computer Science and Engineering or
application areas.
PEO 3:
Equip to adapt and grow with changes in technology and globalization, and to pursue higher
studies and research activities.
PEO 4:
Be capable of productive employment in the field of Computer Science and Engineering with
competing technical expertise, good interpersonal skill.
PEO 5:
Utilize their broad educational experience, ethics, and professionalism to make a positive impact on
their local and professional communities.
PROGRAMME SPECIFIC OUTCOMES (PSOs)
By the time of graduation, the undergraduate ComputerScience and Engineering students
can have the ability of

PSO’s PROGRAMME SPECIFIC OUTCOMES (PSOs)

Designing Computer/Electronic based components which would serve


PSO1
social environment.

Applying the current and gained knowledge and modern techniques


PSO2
not only in the Computers but in all related fields.

PROGRAM OUTCOMES:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineeringsciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide validconclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of thelimitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineeringpractice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainabledevelopment.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms ofthe engineeringpractice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinarysettings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clearinstructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinaryenvironments.
12. Life Long Learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technologicalchange.
CS8381 DATA STRUCTURES LABORATORY LTPC
0042

OBJECTIVES

 To implement linear and non-linear data structures

 To understand the different operations of search trees

 To implement graph traversal algorithms

 To get familiarized to sorting and searching algorithms


1. Array implementation of Stack and Queue ADTs
2. Array implementation of List ADT
3. Linked list implementation of List, Stack and Queue ADTs
4. Applications of List, Stack and Queue ADTs
5. Implementation of Binary Trees and operations of Binary Trees
6. Implementation of Binary Search Trees
7. Implementation of AVL Trees
8. Implementation of Heaps using Priority Queues.
9. Graph representation and Traversal algorithms
10. Applications of Graphs
11. Implementation of searching and sorting algorithms
12. Hashing – any two collision techniques

OUTCOMES: TOTAL: 60 PERIODS

At the end of the course, the students will be able to:

 Write functions to implement linear and non-linear data structure operations

 Suggest appropriate linear / non-linear data structure operations for solving a given problem

 Appropriately use the linear / non-linear data structure operations for a given problem
 Apply appropriate hash functions that result in a collision free scenario for data storage and
retrieval
 Ability to implement searching and sorting algorithms
SUGGESTED SOFTWARE TOOLS
Turbo C, C++ editor for Windows

CO-PO MAPPING:

CO PO PO PO PO PO PO PO PO PO PO PO PO
1 2 3 4 5 6 7 8 9 10 11 12
C207.1 3 2 1 1 1 - - - - - - -
C207.2 3 2 1 1 1 - - - - - - -
C207.3 3 2 1 1 1 - - - - - - -
C207.4 3 2 1 1 1 - - - - - - -
C207.5 3 2 1 1 1 - - - - - - -
C207 3 2 1 1 1 - - - - - - -
LIST OF EXPERIMENTS

Page No
Pr. No: List of Programs
1 Array implementation of Stack and Queue ADTs 2-14

2 Array implementation of List ADT 15-23

3 Linked list implementation of List, Stack and Queue ADTs 24-44

4 Applications of List, Stack and Queue ADTs 45-61

Implementation of Binary Trees and operations of Binary


5 62-66
Trees

6 Implementation of Binary Search Trees 67-71

7 Implementation of AVL Trees 72-79

8 Implementation of Heaps using Priority Queues. 80-84

9 Graph representation and Traversal algorithms 85-102

10 Applications of Graphs 103-107

11 Implementation of searching and sorting algorithms 108-116

12 Hashing – any two collision techniques 117-121

1
EXPT NO:1. a
DATE :25.08.2020

ARRAY IMPLEMENTATION OF STACK ADTS

AIM
To write a c program for array implementation of stack ADTs.

ALGORITHM

push(value) - Inserting value into the stack


Step 1: Check whether stack is FULL. (top == SIZE-1)
Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!"
and terminate the function.
Step 3: If it is NOT FULL, then increment top value by one (top++) and set
stack[top] to value (stack[top] = value).
pop() - Delete a value from the Stack
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is
not possible!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by
one (top--).
display() - Displays the elements of a Stack
Step 1: Check whether stack is EMPTY. (top == -1)

Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the


function.

Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
Step 3: Repeat above step until i value becomes '0'.

2
PROGRAM

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push(); break;
}
case 2:
{
pop(); break;
}
case 3:
{
display(); break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
3
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]); printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

4
OUTPUT

5
6
RESULT:

Thus, the c program for array implementation of stack ADTs is executed successfully.

7
EXPT NO:1. b
DATE :25.08.2020

ARRAY IMPLEMENTATION OF QUEUE ADTS

AIM
To write a c program for array implementation of queue ADTs.

ALGORITHM

enQueue(value) - Inserting value into the queue


Step 1: Check whether queue is FULL. (rear == SIZE-1)
Step 2: If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and
terminate the function.
Step 3: If it is NOT FULL, then increment rear value by one (rear++) and
set queue[rear] = value.
deQueue() - Deleting a value from the Queue
Step 1: Check whether queue is EMPTY. (front == rear)
Step 2: If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then increment the front value by one (front ++). Then
display queue[front] as deleted element. Then check whether both front and rear are
equal (front == rear), if it TRUE, then set both front and rear to '-1' (front = rear = -
1).
display() - Displays the elements of a Queue
Step 1: Check whether queue is EMPTY. (front == rear)
Step 2: If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the
function.
Step 3: If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front+1'.
Step 3: Display 'queue[i]' value and increment 'i' value by one (i++). Repeat the same
until 'i' value is equal to rear (i <= rear)

8
PROGRAM

#include<stdio.h>
#include<conio.h>
#define SIZE 10

void enQueue(int);
void deQueue();
void display();

int queue[SIZE], front = -1, rear = -1;

void main()
{
int value, choice;
clrscr();
while(1)
{
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void enQueue(int value)
{
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else
{
if(front == -1)
front = 0; rear++;
9
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue(){ if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else
{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display()
{
if(rear == -1)
printf("\nQueue is Empty!!!");
else
{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}

10
OUTPUT

11
12
13
RESULT:

Thus, the c program for array implementation of queue ADTs is executed successfully.

14
EXPT NO:2
DATE :01.09.2020

ARRAY IMPLEMENTATION OF LIST ADT

AIM
To write a c program for array implementation of list ADTs.

ALGORITHM

Creation
Step 1: Create number of nodes
Deletion
Step 1: Enter the position to delete
Step 2 : If the position is not in the list, then display “INVALID”
Step 3: Else, delete the value

Search
Step 1: Enter the element to be searched
Step 2: If it is in the list, then display “ element is
found” Step 3: Else, display “ Element not in the list”

Insertion
Step 1: Enter the position to insert the element
Step 2: If the position is not in the list, then display “INVALID”
Step 3: Else, insert the element

15
PROGRAM
#include<stdio.h>
#include<conio.h>
#define MAX 10

void create();
void insert();
void deletion();
void search();
void display();
int a,b[20], n, p, e, f, i, pos;

void main()
{
//clrscr();
int ch;
char g='y';

do
{
printf("\n main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice");
scanf("%d", &ch);

switch(ch)
{
case 1:
create();
break;

case 2:
deletion();
break;

case 3:
search();
break;

case 4:
insert();
break;

16
case 5:

display();
break;

case 6:
exit();
break;

default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:::");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}

void create()
{
printf("\n Enter the number of nodes");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);
}

void deletion()
{
printf("\n Enter the position u want to delete::");
scanf("%d", &pos);

if(pos>=n)
{
printf("\n Invalid Location::");
}
else
{

17
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements after deletion");
for(i=0;i<n;i++)
{
printf("\t%d", b[i]);
}
}
void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);

for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Value is in the %d Position", i);
}
else
{
printf("Value %d is not in the list::", e);
continue;
}
}
}
void insert()
{
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);

if(pos>=n)
{
printf("\n invalid Location::");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{

18
b[i+1]=b[i];
}
printf("\n Enter the element to insert::\n");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion::\n");

display();
}

void display()
{
printf("\n The Elements of The list ADT are:"); for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}

19
OUTPUT:

20
21
22
RESULT:

Thus, the c program for array implementation of list ADTs is executed successfully.

23
EXPT NO:3. a
DATE :08.09.2020

LINKED LIST IMPLEMENTATION OF LIST

AIM
To write c program for singly linked list node to perform operations such as insertions and deletions
dynamically.

ALGORITHM

1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to be done Create a new node and get data part
Insert new node at appropriate position by manipulating address Else if choice = 2
Get node's data to be deleted. Locate the node and delink the node Rearrange the links
Else
Traverse the list from Head node to node which points to null
7. Stop

24
PROGRAM

/* Single Linked List */


#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
#include <string.h> struct node
{
int label;
struct node *next;
};
main()
{
int ch, fou=0; int k;
struct node *h, *temp, *head, *h1;
/* Head node construction */
head = (struct node*) malloc(sizeof(struct node));
head->label = -1; head->next = NULL;

while(-1)
{
clrscr();
printf("\n\n SINGLY LINKED LIST OPERATIONS \n");
printf("1->Add ");
printf("2->Delete ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : "); scanf("%d", &ch); switch(ch)
{
/* Add a node at any intermediate location */
case 1:
printf("\n Enter label after which to add : ");
scanf("%d", &k);
h = head;
fou = 0;
if (h->label == k)
fou = 1;
while(h->next != NULL)
{
if (h->label == k)
{

25
fou=1;
break;
}
h = h->next;
}
if (h->label == k)
fou = 1;
if (fou != 1)
printf("Node not found\n");
else
{

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


printf("Enter label for new node : ");
scanf("%d", &temp->label);
temp->next = h->next;
h->next = temp;
}
break;
/* Delete any intermediate node */
case 2:
printf("Enter label of node to be deleted\n");
scanf("%d", &k);
fou = 0;
h = h1 = head;
while (h->next != NULL)
{
h = h->next;
if (h->label == k)
{
fou = 1;
break;
}
}
if (fou == 0)
printf("Sorry Node not found\n");
else
{
while (h1->next != h) h1 = h1->next;
h1->next = h->next;
free(h);
printf("Node deleted successfully \n");
}
26
break;
case 3:
printf("\n\n HEAD -> ");
h=head;
while (h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL");
break;
case 4: exit(0);
}
}
}

27
OUTPUT

28
29
RESULT:

Thus, the c program to perform operations such as insertions and deletions for singly
linked list node is executed successfully.

30
EXPT NO:3. b
DATE :08.09.2020

LINKED LIST IMPLEMENTATION OF STACK ADT

AIM

To write a c program for linked list implementation of stack ADTs.

ALGORITHM

push(value) - Inserting an element into the Stack

Step 1: Create a newNode with given value.

Step 2: Check whether stack is Empty (top == NULL)

Step 3: If it is Empty, then set newNode → next = NULL.

Step 4: If it is Not Empty, then set newNode → next = top.

Step 5: Finally, set top = newNode.

pop() - Deleting an Element from a Stack


Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!"
and terminate the function

Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top → next'.

Step 5: Finally, delete 'temp' (free(temp)).


display() - Displaying stack of elements
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the
function. Step 3: If it is Not Empty, then define a Node pointer 'temp' and
initialize with top.

Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same
until temp reaches to the first node in the stack (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.

31
PROGRAM

#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*top = NULL;

void push(int);
void pop();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}

32
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)

newNode->next = NULL;
else
newNode->next = top; top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);

}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}
33
OUTPUT

34
35
36
RESULT:

Thus, the c program for linked list implementation of stack ADTs is executed successfully.

37
EXPT NO:3.c
DATE :08.09.2020

LINKED LIST IMPLEMENTATION OF QUEUE ADT

AIM
To write a c program for linked list implementation of queue ADTs.

ALGORITHM

enQueue(value) - Inserting an element into the Queue


Step 1: Create a newNode with given value and set 'newNode → next' to NULL.
Step 2: Check whether queue is Empty (rear == NULL)

Step 3: If it is Empty then, set front = newNode and rear = newNode.


Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.
deQueue() - Deleting an Element from Queue
Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and
terminate from the function
Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).

display() - Displaying the elements of Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.

Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.

38
PROGRAM

#include<stdio.h>
#include<conio.h>

struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;

Void insert(int);
void delete();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
39
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else
{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}

40
OUTPUT

41
42
43
RESULT:

Thus, the c program for linked list implementation of queue ADTs is executed successful

44
EXPT NO:4. a
DATE :15.09.2020

APPLICATIONS OF STACK ADTS

AIM
To convert infix expression to its postfix form using stack operations.

ALGORITHM

1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
If character is an operand print it
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input operator,
Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack and print
it until a left parenthesis is encountered. Do not print the parenthesis.
If character = $ then Pop out all operators, Print them and Stop

45
PROGRAM

/* Conversion of infix to postfix expression */


#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-': return 2; break;
case '*':
case '/': return 4;
break;
case '^':
case '$': return 6; break;
case '(':
case ')':
case '#':
return 1;
break;

}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
46
break;
default:

return 0;
}
}
void convertip(char infix[],char postfix[])
{
int i,symbol,j = 0; stack[++top] = '#';
for(i=0;i<strlen(infix);i++)
{
symbol = infix[i];
if(isoperator(symbol) == 0)
{
postfix[j] = symbol;
j++;
}
else
{
if(symbol == '(') push(symbol);
else if(symbol == ')')
{
while(stack[top] != '(')
{
postfix[j] = pop();
j++;
}
pop(); //pop out (.
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else

{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop();
j++;
}
push(symbol);
}
47
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();
j++;
}

postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top] = item;
}
char pop()
{
char a;
a = stack[top];
top--;
return a;
}

48
OUTPUT

49
RESULT:

Thus, the c program to convert infix expression to its postfix form using stack operations is
executed successfully.
50
EXPT NO:4. b
DATE :15.09.2020

APPLICATIONS OF QUEUE ADTS

AIM
To schedule snapshot of processes queued according to FCFS scheduling. Process
Scheduling
 CPU scheduling is used in multiprogrammed operating systems.
 By switching CPU among processes, efficiency of the system can be improved.
 Some scheduling algorithms are FCFS, SJF, Priority, Round-Robin, etc.
 Gantt chart provides a way of visualizing CPU scheduling and enables to
understand better.
First Come First Serve (FCFS)
 Process that comes first is processed first
 FCFS scheduling is non-preemptive
 Not efficient as it results in long average waiting time.
 Can result in starvation, if processes at beginning of the queue have long
bursts.

ALGORITHM

1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime for each process.
4. The wtime for first process is 0.
5. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
6. Compute average waiting time awat and average turnaround time atur
7. Display the btime, ttime and wtime for each process.
8. Display GANTT chart for the above scheduling
9. Display awat time and atur
10. Stop

51
PROGRAM

/* FCFS Scheduling - fcfs.c */


#include <stdio.h>
struct process
{
int pid;
int btime;
int wtime;
int ttime;
} p[10];

main()
{
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ",(i+1));
scanf("%d", &p[i].btime);
p[i].pid = i+1;
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;
printf("\n FCFS Scheduling\n\n");
for(i=0; i<28; i++)
printf("-");
52
printf("\nProcess B-Time T-Time W-Time\n");
for(i=0; i<28; i++)
printf("-");
for(i=0; i<n; i++)
printf("\n P%d\t%4d\t%3d\t%2d", p[i].pid,p[i].btime,p[i].ttime,p[i].wtime);
printf("\n");
for(i=0; i<28; i++)
printf("-");
printf("\n\nAverage waiting time : %5.2fms", awat);
printf("\nAverage turn around time : %5.2fms\n", atur);
printf("\n\nGANTT Chart\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("|");
for(i=0; i<n; i++)
{
k = p[i].btime/2; for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" ");
printf("|");
}
printf("\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("0");
for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++) printf(" ");
printf("%2d",p[i].ttime);
}
}

53
OUTPUT

54
RESULT:

Thus, the c program to schedule snapshot of processes queued according to FCFS scheduling is
executed successfully.

55
EXPT NO:4.c
DATE :15.09.2020

APPLICATIONS OF LINKED LIST ADTS

AIM
To add any two given polynomial using linked lists.

ALGORITHM

1. Create a structure for polynomial with exp and coeff terms.


2. Read the coefficient and exponent of given two polynomials p and q.
3. While p and q are not null, repeat step 4.
If powers of the two terms are equal then
Insert the sum of the terms into the sum Polynomial
Advance p and q
Else if the power of the first polynomial> power of second then
Insert the term from first polynomial into sum polynomial
Advance p
Else
Insert the term from second polynomial into sum polynomial
Advance q
4. Copy the remaining terms from the non empty polynomial into the sum
polynomial
5. Stop

56
PROGRAM

/* Polynomial Addition */
/* Add two polynomials */
#include <stdio.h>
#include <malloc.h>
#include <conio.h> struct link
{
int coeff; int pow;
struct link *next;
};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
void create(struct link *node)
{
char ch; do
{
printf("\nEnter coefficient: ");
scanf("%d", &node->coeff);
printf("Enter exponent: ");
scanf("%d", &node->pow);
node->next = (struct link*)malloc(sizeof(struct link));
node = node->next; node->next = NULL;
printf("\n continue 1 for y and 0 for no: ");
scanf(“%d”,&cont);
if(cont)
{
node->next = (struct Node*)malloc(sizeof(struct Node));
node = node->next;
node->next = NULL;
}
while(cont);
}
void show(struct link *node)
{
while(node->next!=NULL)
{
printf("%dx^%d", node->coeff, node->pow);
node=node->next;
if(node->next!=NULL)
printf(" + ");
}
}
void polyadd(struct link *poly1, struct link *poly2, struct link *poly)
57
{
while(poly1->next && poly2->next)
{
if(poly1->pow > poly2->pow)
{
poly->pow = poly1->pow;
poly>coeff = poly1->coeff;
poly1 = poly1->next;
}
else if(poly1->pow < poly2->pow)
{
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
}
else
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff + poly2->coeff;
poly1 = poly1->next;
poly2 = poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
}
if(poly2->next)
{
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
}
poly->next = (struct link *)malloc(sizeof(struct link));
poly = poly->next; poly->next = NULL;
58
}
}
main()
{
poly1 = (struct link *)malloc(sizeof(struct link));
poly2 = (struct link *)malloc(sizeof(struct link));
poly = (struct link *)malloc(sizeof(struct link));
printf("Enter 1st Polynomial:");
create(poly1);
printf("\nEnter 2nd Polynomial:");
create(poly2);
printf("\nPoly1: ");
show(poly1);
printf("\nPoly2: ");
show(poly2);
polyadd(poly1, poly2, poly);
printf("\nAdded Polynomial: ");
show(poly);
}

59
OUTPUT

60
RESULT:

Thus, the c program to add any two given polynomial using linked lists is executed successfully.

61
EXPT NO:5
DATE :22.09.2020

IMPLEMENTATION OF BINARY TREE AND ITS OPERATIONS

AIM
To write a c program for implementation of binary tree and its operations.

ALGORITHM

1. Create a structure with key and 2 pointer variable left and right
2. Read the node to be inserted. If (root==NULL)
root=node
else if (root->key < node->key) root->right=NULL
else
Root->left=node
3. For Inorder Traversal Traverse Left subtree Visit root
Traverse Right subtree
4. For Preorder Traversal Visit root
Traverse Left subtree Traverse Right subtree
5. For Postorder Traversal Traverse Left subtree Traverse Right subtree Visit root
6. Stop..

62
PROGRAM

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
}node;
int count=1;
node *insert(node *tree,int digit)
{
if(tree == NULL)
{
tree = (node *)malloc(sizeof(node));
tree->left = tree->right=NULL;
tree->data = digit; count++;
}
else if(count%2 == 0)
tree->left = insert(tree->left, digit);
else
tree->right = insert(tree->right, digit);
return tree;
}
void preorder(node *t)
{
if(t != NULL)
{
printf(" %d", t->data);
preorder(t->left);
preorder(t->right);
}
}
void postorder(node *t)
{
if(t != NULL)
{
postorder(t->left);
postorder(t->right);
printf(" %d", t->data);
}
}
void inorder(node *t)
{
if(t != NULL)
{
inorder(t->left);
printf(" %d", t->data);
inorder(t->right);
}
}
63
main()
{
node *root = NULL;
int digit;
puts("Enter integer:To quit enter 0");
scanf("%d", &digit);
while(digit != 0)
{
root=insert(root,digit);
scanf("%d",&digit);
}
printf("\nThe preorder traversal of tree is:\n");
preorder(root);
printf("\nThe inorder traversal of tree is:\n");
inorder(root);
printf("\nThe postorder traversal of tree is:\n");
postorder(root);
getch();
}

64
OUTPUT

65
RESULT:

Thus, the c program for implementation of binary tree and its operation is executed successfully.

66
EXPT NO:6
DATE :29.09.2020

IMPLEMENTATION OF BINARY SEARCH TREE

AIM
To write a c program for implementation of binary search tree.

ALGORITHM

Creation
Step 1: Create a node with left child and right child with null.
Insertion
Step 1: If Both left child and right child are null, then assign element as root node Step 2:
Else, check with root node (value)

Step 3: If current node (value) is less than root node, then assign it as left child of root node.
Step 4: If current node (value) is greater than root node, then assign it as right child of root
node.

67
PROGRAM

#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
int data;
struct BST*left;
struct BST *right;
}node;

node *create();
void insert(node*,node *);
void preorder(node *);
int main()
{
char ch;
node *root=NULL,*temp;
do
{
temp=create ();
if(root==NU LL)
root=temp;
else
insert(root,temp);
printf("Do you want to enter more(y/n)?");
getchar();
scanf("%c",&ch);
}while(ch=='y'|ch=='Y');
printf("Preorder Traversal: ");
preorder(root);
return 0;
}
node *create()
{
node *temp;
printf("Enter data:");
temp=(node*)malloc(sizeof(node));
scanf("%d",&temp->data);
temp->left=temp->right=NULL;
return temp;
}
void insert(node *root,node *temp)

68
{
if(temp->data<root->data)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}

if(temp->data>root->data)

{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;

}
}

void preorder(node *root)


{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left); preorder(root->right);
}
}

69
OUTPUT:

70
RESULT:

Thus, the c program for implementation of binary search tree is executed successfully.

71
EXPT NO:7
DATE :06.10.2020

IMPLEMENTATION OF AVL TREE

AIM
To write a c program for array implementation of AVL tree.

ALGORITHM

Creation
1.Start
2.Perform standard BST insert for w
3.Starting from w, travel up and find the first unbalanced node. Let z be the first
unbalanced node, y be the child of z that comes on the path from w to z and x be
the grandchild of z that comes on the path from w to z.
4.Re-balance the tree by performing appropriate rotations on the subtree rooted
with z. There can be 4 possible cases that needs to be handled as x, y and z can be
arranged in 4 ways.
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)
5.Stop Program

72
PROGRAM

#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <stdlib.h>
#define CHANGED 0
#define BALANCED 1
typedef struct bnode
{
int data,bfactor; struct bnode *left;
struct bnode *right;
}node;
int height;
void displaymenu()
{
printf("\nBasic Operations in AVL tree");
printf("\n0.Display menu list");
printf("\n1.Insert a node in AVL tree");
printf("\n2.View AVL tree");
printf("\n3.Exit");
}
node* getnode()
{
int size;
node *newnode; size = sizeof(node);
newnode = (node*)malloc(size);
return(newnode);
}
void copynode(node *r, int data)
{
r->data = data;
r->left = NULL; r->right = NULL;
r->bfactor = 0;
}
void releasenode(node *p)
{
free(p);
}
node* searchnode(node *root, int data)
{
if(root!=NULL) if(data < root->data)
root = searchnode(root->left, data);
else if(data > root->data)
root = searchnode(root->right, data);
return(root);
}
void lefttoleft(node **pptr, node **aptr)
{
node *p = *pptr, *a = *aptr;
printf("\nLeft to Left AVL rotation");
p->left = a->right;

73
a->right = p;
if(a->bfactor == 0)
{
p->bfactor = 1;
a->bfactor = -1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}
p = a;
*pptr = p;
*aptr = a;
}
void lefttoright(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *b = *bptr;
printf("\nLeft to Right AVL rotation");
b = a->right;
b->right = p;
if(b->bfactor == 1)
p->bfactor = -1;
else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 1;
else
a->bfactor = 1;
b->bfactor = 0; p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
void righttoright(node **pptr, node **aptr)
{
node *p = *pptr, *a = *aptr;
printf("\nRight to Right AVL rotation");
p->right = a->left;
a->left = p;
if(a->bfactor == 0)
{
p->bfactor = -1;
a->bfactor = 1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}

74
p = a;
*pptr = p;
*aptr = a;
}
void righttoleft(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *b = *bptr;
printf("\nRight to Left AVL rotation");
b = a->left;
a->left = b->right; b->right = a;
p->right = b->left; b->left = p;
if(b->bfactor == -1)
p->bfactor = 1;
else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 0;
b->bfactor = 0; p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
void inorder(node *root)
{
if(root == NULL) return;
inorder(root->left);
printf("\n%4d", root->data);
inorder(root->right);
}
void view(node *root, int level)
{
int k;
if(root == NULL)
return;
view(root->right, level+1);
printf("\n");
for(k=0; k<level; k++)
printf(" ");
printf("%d", root->data);
view(root->left, level+1);
}
node* insertnode(int data, node *p)
{
node *a,*b; if(p == NULL)
{
p=getnode(); copynode(p, data);
height = CHANGED;
return(p);
}
if(data < p->data)
{
p->left = insertnode(data, p->left);

75
if(height == CHANGED)
{
switch(p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED; break;
case 0:
p->bfactor = 1; break;
case 1:
a = p->left;
if(a->bfactor == 1)
lefttoleft(&p, &a); else
lefttoright(&p, &a, &b);
height = BALANCED;
break;
}
}
}
if(data > p->data)
{
p->right = insertnode(data, p->right);
if(height == CHANGED)
{
switch(p->bfactor)
{
case 1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = -1; break;
case -1: a=p->right;
if(a->bfactor == -1)
righttoright(&p, &a);
else
righttoleft(&p, &a, &b);
height=BALANCED; break;
}
}
}
return(p);
}
void main()
{
int data, ch;
char choice = 'y';
node *root = NULL;
displaymenu();
while((choice == 'y') || (choice == 'Y'))
{
printf("\nEnter your choice: ");

76
fflush(stdin);
scanf("%d",&ch);
switch(ch)
{

case 0: displaymenu();
break;
case 1:
printf("Enter the value to be inserted ");
scanf("%d", &data);
if(searchnode(root, data) == NULL)
root = insertnode(data, root);
else
printf("\nData already exists");
break;
case 2:
if(root == NULL)
{
printf("\nAVL tree is empty");
continue;
}
printf("\nInorder traversal of AVL tree");
inorder(root);
printf("\nAVL tree is");
view(root, 1);
break; case 3:
releasenode(root);
exit(0);
}
}
getch();
}

77
OUTPUT

78
RESULT:

Thus, the c program for implementation of AVL tree is executed successfully.

79
EXPT NO:8
DATE :13.10.2020

IMPLEMENTATION OF HEAPS USING PRIORITY QUEUE

AIM
To write a c program for implementation of heaps using priority queue.

ALGORITHM

Creation
Step 1: Create a node with (value and priority) null
Insertion
Step 1: Get value and priority
Step 2: Check the root node

Step 3: If it the root node is null, make the current node as root node. Else, make
the current node as next node of the root node.
Deletion
Step 1: If root node is null then display “ Queue Underflow”. Else, find the
corresponding and delete it

80
PROGRAM

#include<stdio.h>
#include<malloc.h>
void insert();
void del(); void display(); struct node
{
int priority; int info;
struct node *next;
}
*start=NULL,*q,*temp,*new;
typedef struct node N;
int main()
{
int ch; clrscr();
do
{
printf("\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:");
scanf("%d",&ch);
switch(ch)
{
case 1:insert(); break;
case 2:del(); break;
case 3:display(); break;
case 4:
brea k;
}
}
while(ch<4);
}
void insert()
{
int item,itprio; new=(N*)malloc(sizeof(N));
printf("ENTER THE ELT.TO BE INSERTED :\t");
scanf("%d",&item);
printf("ENTER ITS PRIORITY :\t");
scanf("%d",&itprio);
new->info=item; new->priority=itprio;
new->next=NULL;
if(start==NULL )
{
//new->next=start; start=new;
}
else if(start!=NULL&&itprio<=start->priority)
{ new->next=start;
start=new;
}
else
{
q=start;
while(q->next != NULL && q->next->priority<=itprio)
{
81
q=q->next;
}
new->next=q->next;
q->next=new;
}
}
void del()
{
if(start==NULL)
{
printf("\nQUEUE UNDERFLOW\n");
}
else
{
new=start;
printf("\nDELETED ITEM IS %d\n",new->info);
start=start->next;
//free(start);
}
}
void display()
{
temp=start; if(start==NUL L)
printf("QUEUE IS EMPTY\n");
else
{
printf("QUEUE IS:\n");
if(temp!=NULL)
for(temp=start;temp!=NULL;temp=temp->next)
{
printf("\n%d priority =%d\n",temp->info,temp->priority);
//temp=temp->next;
}
}
}

82
OUTPUT

83
RESULT:

Thus, the c program for implementation of heaps using priority queue is executed successfully.

84
EXPT NO:9. a
DATE :20.10.2020

IMPLEMENTATION OF TREE TRAVERSAL

AIM
To write a c program for implementation of tree traversal.

ALGORITHM

Pre-Order Traversal Algorithm (Root, left and Right)


 Visiting the root node.
 Traversing the left sub tree, and finally
 Traversing the right sub tree.

In-Order Traversal Algorithm (Left, root and right)


 Traversing the left sub tree.
 Visiting the root node, and finally
 Traversing the right sub tree
Post-order Traversal Algorithm
 Traversing the left sub tree.
 Traversing the right sub tree, and finally
 Visiting the root node.

85
PROGRAM

#include <stdio.h>
#include <stdlib.h>
struct node { int data;
struct node *leftChild; struct node *rightChild;
};
struct node *root = NULL;
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
//if tree is empty
if(root == NULL)
{
root = tempNode;
}
else
{
current = root;
parent = NULL;
while(1)
{
parent = current;
//go to left of the tree
if(data < parent->data)
{
current = current->leftChild;
//insert to the left
if(current == NULL)
{
parent->leftChild = tempNode;
return;
}
} //go to right of the tree
else
{
current = current->rightChild;
//insert to the right
if(current == NULL)
{
parent->rightChild = tempNode;
return;
}
}
}
}
}
struct node* search(int data)
{
86
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data)
{
if(current != NULL)
printf("%d ",current->data);
//go to left tree
if(current->data > data)
{
current = current->leftChild;
}
//else go to right tree
else
{
current = current->rightChild;
}
//not found
if(current == NULL)
{
return NULL;
}
}
return current;
}
void pre_order_traversal(struct node* root)
{
if(root != NULL)
{
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}
void inorder_traversal(struct node* root)
{
if(root != NULL)
{
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}
void post_order_traversal(struct node* root)
{
if(root != NULL)
{
post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
printf("%d ", root->data);
}
}
int main()
{
87
int i;
int array[7] = { 27, 14, 35, 10, 19, 31, 42 };
for(i = 0; i < 7; i++)
insert(array[i]);
i = 31;
struct node * temp = search(i);
if(temp != NULL)
{
printf("[%d] Element found.", temp->data);
printf("\n");
}else {
printf("[ x ] Element not found (%d).\n", i);
}
i = 15;
temp = search(i);
if(temp != NULL)
{
printf("[%d] Element found.", temp->data);
printf("\n");
}
else
{
printf("[ x ] Element not found (%d).\n", i);
}
Printf("\nPreorder traversal: ");
pre_order_traversal(root);
printf("\nInorder traversal: ");
inorder_traversal(root);
printf("\nPost order traversal: ");
post_order_traversal(root);
return 0;
}

88
OUTPUT

89
RESULT:

Thus, the c program for implementation of binary tree traversal is executed successfully.

90
EXPT NO:9. b
DATE :20.10.2020

IMPLEMENTATION OF BREADTH FIRST TRAVERSAL

AIM
To write a c program for implementation of breadth first traversal.

ALGORITHM

Step 1: Push the root node in the Queue.


Step 2: Loop until the queue is empty.
Step 3: Remove the node from the Queue.
Step 4: If the removed node has unvisited child nodes, mark them as visited and
insert the unvisited children in the queue.

91
PROGRAM

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#defineMAX 5
Struct Vertex
{
char label;
bool visited;
};

//queue variables

int queue[MAX];
int rear = -1;
int front = 0;
int queueItemCount = 0;

//graph variables

//array of vertices
struct Vertex* lstVertices[MAX];

//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;
//queue functions
void insert(int data)
{
queue[++rear] = data;
queueItemCount++;
}

int removeData()
{
queueItemCou nt--;
return queue[front++];
}

bool isQueueEmpty()
{
return queueItemCount == 0;
}

//graph functions

//add vertex to the vertex list


92
void addVertex(char label)
{
struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}

//add edge to edge array


void addEdge(int start,int end)
{
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

//display the vertex


void displayVertex(int vertexIndex)
{
printf("%c ",lstVertices[vertexIndex]->label);
}

//get the adjacent unvisited vertex

int getAdjUnvisitedVertex(int vertexIndex)


{
int i;

for(i = 0; i<vertexCount; i++)


{
if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)
return i;
}

return -1;
}

void breadthFirstSearch()
{
int i;

//mark first node as visited


lstVertices[0]->visited = true;

//display the vertex d


isplayVertex(0);

//insert vertex index in queue


insert(0);
int unvisitedVertex;
93
while(!isQueueEmpty())
{
//get the unvisited vertex of vertex which is at front of the queue
int tempVertex = removeData();

//no adjacent vertex found


while((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1)
{
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
insert(unvisitedVertex);
}

//queue is empty, search is complete, reset the visited flag


for(i = 0;i<vertexCount;i++)
{
lstVertices[i]->visited = false;
}
}

int main()
{
int i, j;

for(i = 0; i<MAX; i++) // set adjacency


{
for(j = 0; j<MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}

addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S – B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D

printf("\nBreadth First Search: ");


breadthFirstSearch();
return 0;
}
94
OUTPUT

95
RESULT:

Thus, the c program for implementation of breadth first traversal is executed successfully.

96
EXPT NO:9.c
DATE :20.10.2020

IMPLEMENTATION OF DEPTH FIRST TRAVERSAL

AIM
To write a c program for implementation of depth first traversal.

ALGORITHM

Step 1: Start by putting any one of the graph's vertices on top of a stack.
Step 2: Take the top item of the stack and add it to the visited list.
Step 3: Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited
list to the top of stack.
Step 4: Keep repeating steps 2 and 3 until the stack is empty.

97
PROGRAM

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

#define MAX 5
struct Vertex
{
char label; bool visited;
};

//stack variables

int stack[MAX];
int top = -1;

//graph variables

//array of vertices
struct Vertex* lstVertices[MAX];

//adjacency matrix
int adjMatrix[MAX][MAX];

//vertex count
int vertexCount = 0;
//stack functions
void push(int item)
{
stack[++top] = item;
}

int pop()
{
return stack[top--];
}

int peek()
{
return stack[top];
}

bool isStackEmpty()
{
return top == -1;
}

//graph functions
98
//add vertex to the vertex list
void addVertex(char label)
{
struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}

//add edge to edge array


void addEdge(int start,int end)
{
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

//display the vertex


void displayVertex(int vertexIndex)
{
printf("%c ",lstVertices[vertexIndex]->label);
}

//get the adjacent unvisited vertex


int getAdjUnvisitedVertex(int vertexIndex)
{
int i;
for(i = 0; i < vertexCount; i++)
{
if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)
{
return i;
}
}
return -1;
}
void depthFirstSearch()
{
int i;
//mark first node as visited lstVertices[0]->visited = true;
//display the vertex displayVertex(0);

//push vertex index in stack


push(0);

while(!isStackEmpty())
{
//get the unvisited vertex of vertex which is at top of the stack
int unvisitedVertex = getAdjUnvisitedVertex(peek());

99
//no adjacent vertex found
if(unvisitedVertex == -1)
{
pop();
}
else
{
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
push(unvisitedVertex);
}
}

//stack is empty, search is complete, reset the visited flag


for(i = 0;i < vertexCount;i++)
{
lstVertices[i]->visited = false;
}
}

int main()
{
int i, j;
for(i = 0; i < MAX; i++) // set adjacency
{f
or(j = 0; j < MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}

addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S – B
addEdge(0, 3); // S - C
addEdge(1, 4); // A – D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D

printf("Depth First Search: ") depthFirstSearch();


return 0;
}

100
OUTPUT

101
RESULT
Thus, the c program for implementation of depth first traversal is executed successfully.

102
EXPT NO:10
DATE :27.10.2020

APPLICATIONS OF GRAPHS

AIM
To find the shortest path for the given graph from a specified source to all other vertices
using Dijkstra’s algorithm.

ALGORITHM

1.Start
2.Obtain no. of vertices and adjacency matrix for the given graph
3.Create cost matrix from adjacency matrix. C[i][j] is the cost of going from
vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is
infinity
4.Initialize visited[] to zero
5.Read source vertex and mark it as visited
6.Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1
from the source vertex
distance[i]=cost[0][i];
7.Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark
visited[w] as 1.
7. Recalculate the shortest distance of remaining vertices from the source.
8. Only, the vertices not marked as 1 in array visited[ ] should be considered for
recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
9. Stop

103
PROGRAM

/* Dijkstra’s Shortest Path */


#include <stdio.h>
#include <conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX], int n, int startnode);
main()
{
int G[MAX][MAX], i, j, n, u; printf("Enter no. of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &G[i][j]);
printf("Enter the starting node: ");
scanf("%d", &u);
dijkstra(G, n, u);
}
void dijkstra(int G[MAX][MAX], int n,int startnode)
{
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX],count, mindistance, nextnode, i, j;
for(i=0; i<n; i++)
for(j=0; j<n; j++)
if(G[i][j] == 0) cost[i][j] = INFINITY;
else
cost[i][j] = G[i][j];
for(i=0; i<n; i++)
{
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
}
distance[startnode] = 0;
visited[startnode] = 1;
count = 1;
while(count < n-1)
{
mindistance = INFINITY;
for(i=0; i<n; i++)
if(distance[i] < mindistance && !visited[i])
104
{
mindistance = distance[i];
nextnode=i;
}
visited[nextnode] = 1;
for(i=0; i<n; i++)
if(!visited[i])
if(mindistance + cost[nextnode][i] < distance[i])
{
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
count++;
}
for(i=0; i<n; i++)
if(i != startnode)
{
printf("\nDistance to node%d = %d", i, distance[i]);
printf("\nPath = %d", i); j = i;
do
{
j = pred[j]; printf("<-%d", j);
} while(j != startnode);
}
}

105
OUTPUT

106
RESULT:

Thus, the c program t o find the shortest path for the given graph from a specified source to all other
vertices using Dijkstra’s algorithm is executed successfully.

107
EXPT NO:11. a
DATE :03.11.2020

IMPLEMENTATION OF BINARY SEARCH

AIM
To write a c program for implementation of binary search.

ALGORITHM

Step 1: Start
Step 2: Declare list x
Step 3: Read elements of list x / Declare elements of list x .
Step 4: Read se.
Step 5: Assign found = False , top = 0 and bot = len(x)-1
Step 6: Check top <= bot and found == false then Go to Step 6.1 else Go to Step 7
Step 6.1 Calculate mid = top+bot/2
Step 6.2 Check If x[mid] == se then set found = True
Step 6.3 Check If se<x[mid] then set bot =mid-1 then Go to Step 6,
Step 6.4 Else, Calculate top = mid+1, then Go to Step 6
Step 7: Check If found == true then Display element is foun Step 8:
Else, Display element is not found.
Step 9: End

108
PROGRAM

#include <stdio.h>

int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d",&array[c]);
printf("Enter value to find\n"); scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last)


{
if (array[middle] < search) first = middle + 1;
else
if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}

109
OUTPUT

110
RESULT:

Thus, the c program for implementation of binary search is executed successfully.

111
EXPT NO:11. b
DATE :03.11.2020

IMPLEMENTATION OF MERGE SORT

AIM
To write a c program for implementation of merge sort.

ALGORITHM

Step 1: Read
Step 2: Declare list x
Step 3: Read elements of list x / Declare elements of list x .
Step 4: if it is only one element in the list it is already sorted, return. Else, go to Step 4
Step 4: Divide the list into left subarray and right sub array.
Step 5: Divide the list recursively into two halves until it can no more divided.
Step 6: Merge the smaller lists into new list in sorted order.
Step 7: End

112
PROGRAM

#include <stdio.h>

#define max 10

int a[11] = {10, 14, 19, 26, 15, 2, 33, 35, 5, 44, 0 };
int b[10];

void merging(int low, int mid, int high)


{ int l1, l2, i;

for(l1 = low, l2 = mid + 1, i = low;


l1 <= mid && l2 <= high; i++)
{
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}

while(l1 <= mid)


b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];

for(i = low; i <= high; i++)


a[i] = b[i];
}

void sort(int low, int high)


{
int mid;

if(low < high)


{
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else { return;
}
}

int main()
{

113
int i;

printf("List before sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");

for(i = 0; i <= max; i++) printf("%d ", a[i]);


}

114
OUTPUT

115
RESULT:

Thus, the c program for implementation of merge sort is executed successfully.


116
EXPT NO:12
DATE :10.11.2020

HASHING – ANY TWO COLLISION TECHNIQUES

AIM
To write a c program for the two collision technique using hashing.

ALGORITHM

1.Create a structure, data (hash table item) with key and value as data.
2.Now create an array of structure, data of some certain size (10, in this case). But, the size of
array must be immediately updated to a prime number just greater
than initial array capacity (i.e 10, in this case).
3.A menu is displayed on the screen.
4.User must choose one option from four choices given in the menu
5.Perform all the operations
6./Stop

117
PROGRAM

/* Open hashing */
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
void main()
{
int a[MAX], num, key, i;
char ans;
int create(int);
void linearprobing(int[], int, int);
void display(int[]);
printf("\nCollision handling by linear probing\n\n");
for(i=0; i<MAX; i++)
a[i] = -1;
do
{
printf("\n Enter number:");
scanf("%d", &num);
key = create(num);
linearprobing(a, key, num);
}
while(MAX);
display(a);
}
int create(int num)
{
int key;
key = num % 10;
return key;
}

void linearprobing(int a[MAX], int key, int num)


{
int flag, i, count = 0;
void display(int a[]);
flag = 0;
if(a[key] == -1)
a[key] = num;
else
{
i=0;
while(i < MAX)
118
{
if(a[i] != -1)
count++;
i++;
}
if(count == MAX)
{
printf("hash table is full");
display(a);
getch();
exit(1);
}
for(i=key+1; i<MAX; i++)
if(a[i] == -1)
{
a[i] = num;
flag = 1;
break;
}
for(i=0; i<key && flag==0; i++ )
if(a[i] == -1)
{
a[i] = num;
flag = 1;
break;
}
}
}
void display(int a[MAX])
{
int i;
printf("\n Hash table is:");

for(i=0; i<MAX; i++)


printf("\n %d\t\t%d",i,a[i]);
}

119
OUTPUT

120
RESULT:

Thus, the c program for the two collision technique using hashing is executed successfully.

121

You might also like