(An Iso 9001-2008 Certified Institution) (Approved by AICTE, New Delhi & Affiliated To Anna University)
(An Iso 9001-2008 Certified Institution) (Approved by AICTE, New Delhi & Affiliated To Anna University)
(An Iso 9001-2008 Certified Institution) (Approved by AICTE, New Delhi & Affiliated To Anna University)
NAME : G. PREETHI
REGISTER NO : 113019104068
ROLL NO : VH-10050
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 .
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.
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
Date:…………….……..
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA
ENGINEERING COLLEGE
INSTITUTION VISION
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
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.
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
PROGRAM OUTCOMES:
OBJECTIVES
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
1
EXPT NO:1. a
DATE :25.08.2020
AIM
To write a c program for array implementation of stack ADTs.
ALGORITHM
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
AIM
To write a c program for array implementation of queue ADTs.
ALGORITHM
8
PROGRAM
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();
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
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
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
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
{
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
AIM
ALGORITHM
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 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
AIM
To write a c program for linked list implementation of queue ADTs.
ALGORITHM
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
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
}
}
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
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
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
AIM
To add any two given polynomial using linked lists.
ALGORITHM
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
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
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;
}
}
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
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:
79
EXPT NO:8
DATE :13.10.2020
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
AIM
To write a c program for implementation of tree traversal.
ALGORITHM
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
AIM
To write a c program for implementation of breadth first traversal.
ALGORITHM
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
return -1;
}
void breadthFirstSearch()
{
int i;
int main()
{
int i, j;
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
95
RESULT:
Thus, the c program for implementation of breadth first traversal is executed successfully.
96
EXPT NO:9.c
DATE :20.10.2020
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;
}
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);
}
}
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
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
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
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);
109
OUTPUT
110
RESULT:
111
EXPT NO:11. b
DATE :03.11.2020
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];
int main()
{
113
int i;
114
OUTPUT
115
RESULT:
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;
}
119
OUTPUT
120
RESULT:
Thus, the c program for the two collision technique using hashing is executed successfully.
121