Data Structures Lab Manual PDF
Data Structures Lab Manual PDF
PREPARED BY
1
SEC CSE/III DS LAB MANUAL
PREFACE
engineering for Data Laboratory (CS 2208). This lab manual can be used as
instructional book for students, staff and instructors to assist in performing and
understanding the experiments. In the first part of the manual, experiments as per
syllabus are described and in the second part of the manual, experiments that are beyond
the syllabus but expected for university laboratory examination are displayed. This
manual will be available in electronic form from College’s official website, for the
betterment of students.
2
SEC CSE/III DS LAB MANUAL
ACKNOWLEDGEMENT
With great pleasure and deep sense of gratitude, we take this opportunity to
express my hearty thanks and deep regards to the support offered by the chairman Shri.
A.Srinivasan.
We also take this opportunity to express a deep sense of gratitude to our Principal
We extend our hearty thanks to our head of the department Ms.S.Jayanthi for her
Finally the valuable comments from fellow faculty and assistance provided by
the department are highly acknowledged. We would like to thank everyone who helped
Last but not least we express our heartfelt thanks to Lord Almighty for being
3
SEC CSE/III DS LAB MANUAL
TABLE OF CONTENTS
REFERENCES
4
SEC CSE/III DS LAB MANUAL
CHAPTER 1
Turbo C language
MAIN FEATURES
-in functions and operators can be used to
write any complex program
ns that C programs written for one computer can be run
onanother with little or no modification.
ADVANTAGES
-level languages because the
language set is relatively small and very efficient
is due to its
ability to use/work with assembly and communicate directly with controllers, processors
and other devices.
LIMITATIONS
Weak text processing capabilities - C's string library is extremely primitive (it doesn't
even define an actual string type), and text processing is labor-intensive and error-prone.
Security and safety issues- several library functions (gets() being the most notorious)
provide easy exploits for malware, and anything involving pointers is going to be unsafe
(it's hard to guard against being passed an invalid pointer);
Weak memory management capabilities - Like text processing, managing memory in
C is labor-intensive and error-prone
No built-in collections library - C doesn't provide readymade collections (lists,
queues, stacks, etc.), meaning you have to roll your own.
No built-in support for networking, sound, graphics, etc. - C is a product of the
early 1970s and it shows; byte streams are about the highest level of abstraction you're
going to find in the C library.
5
SEC CSE/III DS LAB MANUAL
APPLICATIONS
6
SEC CSE/III DS LAB MANUAL
CHAPTER 2
SYLLABUS
2.Represent a polynomial as a linked list and write functions for polynomial addition.
4.Implement a double-ended queue (dequeue) where insertion and deletion operations are
10.Implement prim’s algorithm using priority queue to find MST of an Undirected graph.
7
SEC CSE/III DS LAB MANUAL
CHAPTER 3
SYSTEM REQUIREMENTS
1 HARDWARE REQUIREMENTS:
2 SOFTWARE REQUIREMENTS:
TURBO C
8
SEC CSE/III DS LAB MANUAL
CHAPTER 4
ABOUT THE DATA STRUCTURES LABORATORY
AIM
LEARNING OBJECTIVE
9
SEC CSE/III DS LAB MANUAL
Date
DESCRIPTION
Singly Linked list is a linked list in which each node contains only one link field
pointing to the next field.The possible operations are:
OBJECTIVE
The main objective is to write program to implement singly linked list
which can create and insert a element with a single link.
delnode()-Delete the node from the list if available, otherwise display error message
10
SEC CSE/III DS LAB MANUAL
This program get input from user and create a linked list with delete and insert
option and also display the node in the list as an output.
ADVANTAGES
Singly linked list can store data in non-contiguous locations. Thus there is no need
of compaction of memory,when some large related data is to be stored into the
memory.
LIMITATIONS
There is no way to go back from one node to previous one. Only forward
traversal is possible.
APPLICATIONS
11
SEC CSE/III DS LAB MANUAL
A list is not as efficient, however, at doing things like adding on the end of the
container, due to the necessity to progress all the way through the list
ALGORITHM
1. Start
2. Creation: Get the number of elements, and create the nodes having structures
DATA LINK and store the element in Data field, link them together to form a
linked list.
3. Insertion: Get the number to be inserted and create a new node, store the value
in DATA field. And insert the node in the required position.
4. Deletion: Get the number to be deleted. Search the list from the beginning and
locate the node then delete the node.
5. Display: Display all the nodes in the list.
6. Stop.
PROGRAM
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void create();
void insert();
void delet();
void display();
struct node
{
int data;
struct node *link;
};
struct node *first=NULL,*last=NULL,*next,*prev,*cur;
void create()
{
cur=(struct node*)malloc(sizeof(struct node));
printf("\nENTER THE DATA: ");
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;
}
void insert()
{
12
SEC CSE/III DS LAB MANUAL
int pos,c=1;
cur=(struct node*)malloc(sizeof(struct node));
printf("\nENTER THE DATA: ");
scanf("%d",&cur->data);
printf("\nENTER THE POSITION: ");
scanf("%d",&pos);
if((pos==1) &&(first!=NULL))
{
cur->link = first;
first=cur;
}
else
{
next=first;
while(c<pos)
{
prev=next;
next=prev->link;
c++;
}
if(prev==NULL)
{
printf("\nINVALID POSITION\n");
}
else
{
cur->link=prev->link;
prev->link=cur;
}
}
}
void delet()
{
int pos,c=1;
printf("\nENTER THE POSITION : ");
scanf("%d",&pos);
if(first==NULL)
{
printf("\nLIST IS EMPTY\n");
}
else if(pos==1 && first->link==NULL)
{
printf("\n DELETED ELEMENT IS %d\n",first->data);
free(first);
first=NULL;
}
else if(pos==1 && first->link!=NULL)
13
SEC CSE/III DS LAB MANUAL
{
cur=first;
first=first->link;
cur->link=NULL;
printf("\n DELETED ELEMENT IS %d\n",cur->data);
free(cur);
}
else
{
next=first;
while(c<pos)
{
cur=next;
next=next->link;
c++;
}
cur->link=next->link;
next->link=NULL;
if(next==NULL)
{
printf("\nINVALID POSITION\n");
}
else
{
printf("\n DELETED ELEMENT IS %d\n",next->data);
free(next);
}
}
}
void display()
{
cur=first;
while(cur!=NULL)
{
printf("\n %d",cur->data);
cur=cur->link;
}
}
void main()
{
int ch;
clrscr();
printf("\n\nSINGLY LINKED LIST");
do
{
printf("\n\n1.CREATE\n2.INSERT\n3.DELETE\n4.EXIT");
14
SEC CSE/III DS LAB MANUAL
printf("\n\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
display();
break;
case 2:
insert();
display();
break;
case 3:
delet();
display();
break;
case 4:
exit(0);
default:
printf("INVALID CHOICE...");
}
} while(1);
}
OUTPUT
1.CREATE
2.INSERT
3.DELETE
4.EXIT
10
1.CREATE
2.INSERT
3.DELETE
4.EXIT
15
SEC CSE/III DS LAB MANUAL
ENTER THE POSITION: 2
10
20
1.CREATE
2.INSERT
3.DELETE
4.EXIT
10
20
30
1.CREATE
2.INSERT
3.DELETE
4.EXIT
DELETED ELEMENT IS 20
10
30
1.CREATE
2.INSERT
3.DELETE
4.EXIT
RESULT
16
SEC CSE/III DS LAB MANUAL
VIVA QUESTIONS
A linked list is a linear collection of data elements, called nodes, where the linear
order is given by pointers. Each node has two parts first part contain the information of
the element second part contains the address of the next node in the list.
It has only head part and corresponding references to the next nodes.
Single linked list- Here, the pointer can only move in one direction.
Double linked list- Here, the pointer can move in forward or backward direction.
Circular linked list- Here, the address of the last node points to the first node of the list so
as to make it a circular linked list.
`According to Access strategies Linked list is a linear one. According to Storage Linked
List is a Non-linear one.
POSSIBLE QUESTIONS
3.Implement a singly linked list-By displaying all nodes present in the list.
17
SEC CSE/III DS LAB MANUAL
Date
DESCRIPTION
A doubly linked list is a list that contains links to next and previous nodes. Unlike
singly
linked lists where traversal is only one way, doubly linked lists allow traversals in both
ways. It can perfor create ,delete,insert and display operation in which the Create
operation will process the following steps.
1. Create the new node and allocate memory for the new node.
2. Read the data in the new node.
3. Assign Flink and Blink as NULL.
4. Assign current as new.
OBJECTIVE
The main objective is to write program to implement Doubly linked list which can
create and insert ,delete and display present in the list.
typedef struct
node {
void* data;
struct node* next;
struct node*
prev;
} node;
18
SEC CSE/III DS LAB MANUAL
This program get input from user and create a linked list with delete and insert
option and also display the node in the list as an output.
ADVANTAGES
We can traverse in both directions i.e. from starting to end and as well as from
end to starting.
It is easy to reverse the linked list.
If we are at a node, then we can go to any node. But in linear linked list, it is not
possible to reach the previous node.
DISADVANTAGES
1. It requires more space per space per node because one extra field is required
for pointer to previous node.
Insertion and deletion take more time than linear linked list because more pointer
operations are required than linear linked list.
APPLICATION
Doubly linked lists are also widely used in many applications that deals with
dynamic memory allocation and deallocation.
19
SEC CSE/III DS LAB MANUAL
Although an additional pointer is used to allow traversal in both ways, Doubly
linked lists are ideal for applications that requires frequent insertions and
deletions from a list.
ALGORITHM
1. Start
2. Creation: Get the number of elements to create the list. Then create the node
having the structure BLINK DATA FLINK and store the elements in Data field.
Link them together to form a doubly linked list. .
3. Insertion: Get the number to be Inserted, create a new node to store the value.
Search the list and insert the node in its right position.
4. Deletion: Get the number to be deleted. Search the list from the beginning and
try to locate node p with DATA. If found then . delete the node.
5. FLINK P’s previous node to P’s Next node. BLINK P’s Next node to P’s
Previous node else display “Data not Found”.
6. Display: Display all the nodes in the list.
7. Stop.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
#define NULL 0
struct linkedlist
{
int item;
struct linkedlist *right,*left;
};
typedef struct linkedlist node;
void main()
{
node *start,*end;
int choice;
int menu(void);
node *create(node **lastnode);
void display(node *first,node *last);
void insert(node **first,node **last);
void del(node **first,node **last);
clrscr();
20
SEC CSE/III DS LAB MANUAL
printf("\n DOUBLY LINKED LIST");
printf("\n ******************");
do
{
printf("\n Main menu");
printf("\n 1.Create \n 2.Insert \n 3.Delete \n 4.Display \n 5.Exit");
choice =menu();
switch(choice)
{
case 1:
printf("\n Enter the data(0 to stop):");
start=create(&end);
continue;
case 2:
insert(&start,&end);
printf("\n");
continue;
case 3:
del(&start,&end);
printf("\n");
continue;
case 4:
display(start,end);
printf("\n");
continue;
case 5:
exit(0);
default:
printf("\n INVALID CHOICE...");
}
} while(1);
}
int menu()
{
int choice;
do
{
printf("\n Enter your choice:");
scanf("%d",&choice);
if(choice<1||choice>5)
printf("\n Wrong choice");
}
while(choice<1||choice>5);
return(choice);
}
21
SEC CSE/III DS LAB MANUAL
{
node *temp,*firstnode;
int info;
*lastnode=NULL;
firstnode=NULL;
scanf("%d",&info);
while(info!=0)
{
temp=(node *)malloc(sizeof(node));
temp->item=info;
temp->right=NULL;
if(firstnode==NULL)
{
temp->left=NULL;
firstnode=temp;
}
else
{
temp->left=(*lastnode);
(*lastnode)->right=temp;
}
(*lastnode)=temp;
scanf("%d",&info);
}
if(firstnode!=NULL)
(*lastnode)=temp;
return(firstnode);
}
22
SEC CSE/III DS LAB MANUAL
node *newnode;
int newitem;
int position;
node *temp;
int i;
printf("\n New data item:");
scanf("%d",&newitem);
do
{
printf("\n Position of insertion:");
scanf("%d",&position);
}
while(position<=0);
if(((*first)==NULL)||(position==1))
{
newnode=(node *)malloc(sizeof(node));
newnode->item=newitem;
newnode->right=*first;
newnode->left=NULL;
if((*first)!=NULL)
(*first)->left=newnode;
else
(*last)=newnode;
*first=newnode;
}
else
{
i=1;
temp=*first;
while((i<position-1)&&(temp->right!=NULL))
{
i++;
temp=temp->right;
}
newnode=(node *)malloc(sizeof(node));
newnode->item=newitem;
newnode->right=temp->right;
if(temp->right!=NULL)
temp->right->left=newnode;
newnode->left=temp;
temp->right=newnode;
}
if(newnode->right==NULL)
*last=newnode;
}
23
SEC CSE/III DS LAB MANUAL
node *temp,*prev;
int target;
printf("\n Enter the data to be deleted:");
scanf("%d",&target);
if(*first==NULL)
printf("\n List is empty");
else if((*first)->item==target)
{
if((*first)->right==NULL)
*first=*last=NULL;
else
{
*first=(*first)->right;
(*first)->left=NULL;
}
}
else
{
temp=*first;
prev=NULL;
while((temp->right!=NULL)&&(temp->item!=target))
{
prev=temp;
temp=temp->right;
}
if(temp->item!=target)
printf("\n Element not found");
else
{
if(temp==*last)
*last=prev;
else
temp->right->left=temp->left;
prev->right=temp->right;
}
}
}
Output:
24
SEC CSE/III DS LAB MANUAL
5.Exit
Enter your choice:1
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:2
Position of insertion:3
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
10 20 30
Backward traversal
30 20 10
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:2
Position of insertion:2
Main menu
25
SEC CSE/III DS LAB MANUAL
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
10 40 20 30
Backward traversal
30 20 40 10
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:3
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
10 20 30
Backward traversal
30 20 10
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:5
RESULT
Thus the operation of Doubly Linked List has been implemented successfully
in C program.
26
SEC CSE/III DS LAB MANUAL
VIVA QUESTIONS
It is a collection of data elements called nodes, where each node is divided into three
parts
A linked list is a very ideal data structure because it can be modified easily. This
means that modifying a linked list works regardless of how many elements are in the list.
POSSIBLE QUESTIONS
27
SEC CSE/III DS LAB MANUAL
Date
DESCRIPTION
Read the coefficient and power of the polynomial equation one and assign it's
elements into a linked list. Sorting the first polynomial in power order wise. Compare the
first node's power with next nodes power, if second node's power is greater than first
Node then swap. Repeat the process until we get the proper order.Add the two
polynomial.If power parts of the two lists are equal, then add the coefficients
OBJECTIVE
The main objective is to write a program to implement the addition of two
polynomial equations.
This program get variables as input and perform polynomial addition and produce
the result as an output.
ADVANTAGES
Only one pointer is needed to point to first term of the polynomial.
28
SEC CSE/III DS LAB MANUAL
The insertion and deletion operations can be carried out very easily without
movement of data.
DISADVANTAGES
We cannot access any term randomly or directly we have to go from start node
always.
APPLICATIONS
Variou operations like addition,multiplication with polynomials can perform with
the linked list.To get better proficiency in processing,each polynomial is stored in
decreasing order. These arrangements of polynomial in series allow easy
operation on them.
P(X) = anxne+an-1xn-1e+…+a1x1e +a
Where ai – nonzero coefficients,0<i<n
ei – exponent
4. Each node in the polynomial is considered as a node .Each node contains three fields
Node Structure
Coefficient Exponent Link
7. Q:3x3+4x2+x
8. The resultant polynomial can be represented like this. R:3x3+9x2+7x+7
29
SEC CSE/III DS LAB MANUAL
9. Stop.
PROGRAM
#include<stdio.h>
#include<conio.h>
struct polyadd
{
int coff;
int pow;
struct polyadd *link;
}*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2;
typedef struct polyadd bar;
int temp1,temp2;
void main()
{
void create(void);
void display(void);
void polyaddtion(void);
void sorting(void);
clrscr();
printf("\nEnter the elements of the first polynomial :");
node = (bar *) malloc(sizeof (bar));
start1=node;
if (start1==NULL)
{
printf("\nUnable to create memory.");
getch();
exit();
}
create();
printf("\nEnter the elements of the second polynomial :");
node = (bar *) malloc(sizeof (bar));
start2=node;
if (start2==NULL)
{
printf("\nUnable to create memory.");
getch();
exit();
}
create();
clrscr();
printf("\nThe elements of the polynomial first are :");
ptr=start1;
display();
printf("\nThe elements of the polynomial second are :");
ptr=start2;
display();
30
SEC CSE/III DS LAB MANUAL
printf("\nThe first sorted list is :");
ptr=start1;
sorting();
ptr=start1;
display();
void create()
{
char ch;
while(1)
{
printf("\nEnter the coff and pow :");
scanf("%d%d",&node->coff,&node->pow);
if (node->pow==0 )
{
ptr=node;
node=(bar *)malloc(sizeof(bar));
node=NULL;
ptr->link=node;
break;
}
printf("\nDo u want enter more coff ?(y/n) :");
fflush(stdin);
scanf("%c",&ch);
if (ch=='n' )
{
ptr=node;
node=(bar *)malloc(sizeof(bar));
node=NULL;
ptr->link=node;
break;
}
ptr=node;
node=(bar *)malloc(sizeof(bar));
ptr->link=node;
}
31
SEC CSE/III DS LAB MANUAL
}
void display()
{
int i=1;
while(ptr!=NULL )
{
if(i!=1)
printf("+ ");
printf(" %dx^%d ",ptr->coff,ptr->pow);
ptr=ptr->link;
i++;
}
}
void sorting()
{
for(;ptr->coff!=NULL;ptr=ptr->link)
for(ptr2=ptr->link;ptr2->coff!=NULL;ptr2=ptr2->link)
{
if(ptr->pow>ptr2->pow)
{
temp1=ptr->coff;
temp2=ptr->pow;
ptr->coff=ptr2->coff;
ptr->pow=ptr2->pow;
ptr2->coff=temp1;
ptr2->pow=temp2;
}
}
}
void polyaddtion()
{
node=(bar *)malloc (sizeof(bar));
start3=node;
ptr1=start1;
ptr2=start2;
while(ptr1!=NULL && ptr2!=NULL)
{
ptr=node;
if (ptr1->pow > ptr2->pow )
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link;
}
else if ( ptr1->pow < ptr2->pow )
32
SEC CSE/III DS LAB MANUAL
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link;
}
else
{
node->coff=ptr2->coff+ptr1->coff;
node->pow=ptr2->pow;
ptr1=ptr1->link;
ptr2=ptr2->link;
}
node=(bar *)malloc (sizeof(bar));
ptr->link=node;
}
if (ptr1==NULL)
{
while(ptr2!=NULL)
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link;
ptr=node;
node=(bar *)malloc (sizeof(bar));
ptr->link=node;
}
}
else if (ptr2==NULL)
{
while(ptr1!=NULL)
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link;
ptr=node;
node=(bar *)malloc (sizeof(bar));
ptr->link=node;
}
}
node=NULL;
ptr->link=node;
}
Output:
33
SEC CSE/III DS LAB MANUAL
The elements of the polynomial first are : 10x^3 + 20x^2 + 10x^1 + 5x^0
The elements of the polynomial second are : 30x^3 + 20x^2 + 10x^1 + 5x^0
The first sorted list is : 5x^0 + 10x^1 + 20x^2 + 10x^3
The second sorted list is : 5x^0 + 10x^1 + 20x^2 + 30x^3
The sum of the two lists are : 10x^0 + 20x^1 + 40x^2 + 40x^3
RESULT
Thus the addition of two polynomial equations has been implemented
successfully in C
Program.
VIVA QUESTIONS
1.How a polynomial can be represented?
A polynomial can be represented in an array or in a linked list by simply storing
the coefficient and exponent of each term.
34
SEC CSE/III DS LAB MANUAL
For any polynomial operation , such as addition or multiplication of polynomials ,
It will find that the linked list representation is more easier to deal with.First of all note
that in a polynomial all the terms may not be present, especially if it is going to be a very
high order polynomial.
SAMPLE QUESTIONS
1.Write a program to perform polynomial addition.
2.Write a program to perform polynomial addition with linked list.
35
SEC CSE/III DS LAB MANUAL
Date
DESCRIPTION
A stack is an ordered collection of homogeneous data elements where the
insertion and deletion operations occur at one end only, called the top of the stack. Infix
to Postfix Conversion is an arithmetic expression is the combination of variables,
constants and arithmetic operators.Variables and constants may be preceded by unary
operators like –, +. To evaluate any arithmetic expression, the order of precedence and
associativity of the operators
should be known.
OBJECTIVE
The main objective is to write a program to implement Stack and use it to convert
infix to postfix expression
This program get variables as input and perform conversion of infix expression
with the stack and produce postfix expression as an output.
ADVANTAGES
The advantage of this method is that the implementation of the stack using an
array
is easy.
36
SEC CSE/III DS LAB MANUAL
DISADVANTAGES
we cant resize,no searching,takes more memory means we create memory
statically.
Memory space is wasted (because of storing less number of items in the array
than the maximum size of the array).
Insertion and deletion operations in a stack using an array involves more data
movements.
APPLICATIONS OF STACK
Infix to postfix conversion.
ALGORITHM
1.Start the program.
2 .The expression is to be read from left to right.
6. If the input symbol read is a closing parenthesis ‘)’ then pop all operators from
the stack, place them in postfix expression till the opening parenthesis ‘(‘ is not
popped.
37
SEC CSE/III DS LAB MANUAL
7.The ‘(‘ should not be placed in the postfix expression.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
#define N 64
#define LP 10
#define RP 20
#define OPERATOR 30
#define OPERAND 40
#define LPP 0
#define AP 1
#define SP AP
#define MP 2
#define DP MP
#define REMP 2
#define NONE 9
void infixtopostfix(void);
int gettype(char);
void push(char);
char pop(void);
int getprec(char);
void main()
{
char ch;
do
{
top=-1;
printf("\nEnter an infix expression\n");
fflush(stdin);
38
SEC CSE/III DS LAB MANUAL
gets(infix);
infixtopostfix();
printf("\ninfix = %s\npost fix =%s\n",infix,postfix);
printf("\nDo you wish to continue(y/n):");
ch=getche();
} while(ch=='Y' || ch=='y');
}
void infixtopostfix(void)
{
int i,p,l,type,prec;
char next;
i=p=0;
l=strlen(infix);
while(i<l)
{
type=gettype(infix[i]);
switch(type)
{
case LP:
push(infix[i]);
break;
case RP:
while((next=pop())!='(')
postfix[p++]=next;
break;
case OPERAND:
postfix[p++]=infix[i];
break;
case OPERATOR:
prec=getprec(infix[i]);
while(top>-1 && prec <= getprec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
}
i++;
}
while(top>-1)
postfix[p++]=pop();
postfix[p]='\0';
}
39
SEC CSE/III DS LAB MANUAL
char pop(void)
{
if(top<=-1)
{
printf("\nStack is empty\n");
exit(0);
}
else
return(stack[top--]);
}
40
SEC CSE/III DS LAB MANUAL
int getprec(char sym)
{
switch(sym)
{
case '(':
return(LPP);
case '+':
return(AP);
case '-':
return(SP);
case '*':
return(MP);
case '/':
return(DP);
case '%':
return(REMP);
default :
return(NONE);
}
}
OUTPUT
infix = a*b+c*d/e
post fix =ab*cd*e/+
infix = a+b
post fix =ab+
RESULT
Thus the infix to postfix expression conversion has been implemented
successfully using stack.
41
SEC CSE/III DS LAB MANUAL
VIVA QUESTIONS
1. What is difference between Stack and Queue data structure ?
One of the classical datastrucutre interview question. I guess every one know,
No? Any way main difference is that Stack is LIFO(Last In First Out) data structure
while Queue is a FIFO(First In First Out) data structure.
2.What is LIFO?
LIFO is short for Last In First Out, and refers to how data is accessed, stored and
retrieved. Using this scheme, data that was stored last , should be the one to be extracted
first. This also means that in order to gain access to the first data, all the other data that
was stored before this first data must first be retrieved and extracted.
3.What is a stack?
A stack is a data structure in which only the top element can be accessed. As data
is stored in the stack, each data is pushed downward, leaving the most recently added
data on top.
POSSIBLE QUESTIONS
2.write a program to implement a stack and use it to convert from infix to postfix
expression.
42
SEC CSE/III DS LAB MANUAL
DESCRIPTION
Queue operations, we can maintain two pointers –qfront and qback as we
had done for the case of array implementation of queues.
For the Enqueue operation, the data is first loaded on a new node.If the queue is
empty, then after insertion of the first node, both qfront and qback are made to point to
this node, otherwise, the new node is simply appended and qback updated.
In Dequeue function, first of all check if at all there is any element. If there is
none, we would have *qfront as NULL, and so report queue to be empty, otherwise
return the data element, update the *qfront pointer and free the node. Special care has to
be taken if it was the only node in the queue.
OBJECTIVE
This program get elements as input and perform insertion and deletion operation
in a double end queue namely Enqueqe and Dequeue operation respectively and display
the queue with its element as anression as an output.
43
SEC CSE/III DS LAB MANUAL
ADVANTAGES
Insertion and deletion carried out both the Ends.
DISADVANTAGES
APPLICATION
ALGORITHM
Step 3: Enter the choice Input restricted dequeue and Output restricted dequeue.
Step 4: If the choice is Input restricted dequeue, then perform the following operations:
1.Insert at
right 2.Delete from left 3.Delete from right 4.Display 5.Quit.
Step 5: If the choice is Output restricted dequeue, then perform the following operations:
1.Insert
at right 2.Insert at left 3.Delete from left 4.Display 5.Quit.
44
SEC CSE/III DS LAB MANUAL
PROGRAM
# include<stdio.h>
# define MAX 5
void input_que();
void output_que();
void insert_right();
void insert_left();
void delete_left();
void delete_right();
void display_queue();
int deque_arr[MAX];
int left = -1;
int right = -1;
void main()
{
int choice;
printf("1.Input restricted dequeue\n");
printf("2.Output restricted dequeue\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
input_que();
break;
case 2:
output_que();
break;
default:
printf("Wrong choice\n");
}
}
void input_que()
{
int choice;
while(1)
{
printf("1.Insert at right\n");
printf("2.Delete from left\n");
printf("3.Delete from right\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
45
SEC CSE/III DS LAB MANUAL
scanf("%d",&choice);
switch(choice)
{
case 1:
insert_right();
break;
case 2:
delete_left();
break;
case 3:
delete_right();
break;
case 4:
display_queue();
break;
case 5:
exit();
default:
printf("Wrong choice\n");
}
}
}
void output_que()
{
int choice;
while(1)
{
printf("1.Insert at right\n");
printf("2.Insert at left\n");
printf("3.Delete from left\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert_right();
break;
case 2:
insert_left();
break;
case 3:
delete_left();
break;
case 4:
display_queue();
46
SEC CSE/III DS LAB MANUAL
break;
case 5:
exit();
default:
printf("Wrong choice\n");
}
}
}
void insert_right()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{
printf("Queue Overflow\n");
return;
}
if (left == -1) /* if queue is initially empty */
{
left = 0;
right = 0;
}
else
if(right == MAX-1) /*right is at last position of queue */
right = 0;
else
right = right+1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[right] = added_item ;
}
void insert_left()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{
printf("Queue Overflow \n");
return;
}
if (left == -1)/*If queue is initially empty*/
{
left = 0;
right = 0;
}
else
if(left== 0)
left=MAX-1;
47
SEC CSE/III DS LAB MANUAL
else
left=left-1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[left] = added_item ;
}
void delete_left()
{
if (left == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[left]);
if(left == right) /*Queue has only one element */
{
left = -1;
right=-1;
}
else
if(left == MAX-1)
left = 0;
else
left = left+1;
}
void delete_right()
{
if (left == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[right]);
if(left == right) /*queue has only one element*/
{
left = -1;
right=-1;
}
else
if(right == 0)
right=MAX-1;
else
right=right-1;
}
void display_queue()
48
SEC CSE/III DS LAB MANUAL
{
int front_pos = left,rear_pos = right;
if(left == -1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
{
while(front_pos <= rear_pos)
{
printf("%d ",deque_arr[front_pos]);
front_pos++;
}
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",deque_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",deque_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
Output - 1:
49
SEC CSE/III DS LAB MANUAL
3.Delete from right
4.Display
5.Quit
Enter your choice : 1
Input the element for adding in queue : 20
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 1
Input the element for adding in queue : 30
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 1
Input the element for adding in queue : 40
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 4
Queue elements :
10 20 30 40
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 2
Element deleted from queue is : 10
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 4
Queue elements :
20 30 40
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 3
50
SEC CSE/III DS LAB MANUAL
Element deleted from queue is : 40
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 4
Queue elements :
20 30
1.Insert at right
2.Delete from left
3.Delete from right
4.Display
5.Quit
Enter your choice : 5
Output - 2:
1.Input restricted dequeue
2.Output restricted dequeue
Enter your choice : 2
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 1
Input the element for adding in queue : 10
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 1
Input the element for adding in queue : 20
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 4
Queue elements :
10 20
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
51
SEC CSE/III DS LAB MANUAL
Enter your choice : 2
Input the element for adding in queue : 5
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 4
Queue elements :
5 10 20
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 3
Element deleted from queue is : 5
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 4
Queue elements :
10 20
1.Insert at right
2.Insert at left
3.Delete from left
4.Display
5.Quit
Enter your choice : 5
RESULT
Thus the double-ended queue where insertion and deletion operations are
possible at
both the ends has been implemented successfully in this program.
VIVA QUESTIONS
1.What is a queue?
A queue is a data structure that can simulates a list or stream of data. In this
structure, new elements are inserted at one end and existing elements are removed from
the other end.
52
SEC CSE/III DS LAB MANUAL
2.What is FIFO?
FIFO is short for First-in, First-out, and is used to represent how data is accessed
in a queue. Data has been inserted into the queue list the longest is the one that is
removed first.
POSSIBLE QUESTION
53
SEC CSE/III DS LAB MANUAL
DESCRIPTION
Expression tree is a binary tree in which the leaf node are operands and the
interior nodes are operators. Like binary tree,expression tree can also be travesed by
inorder,preorder and post order traversal.
OBJECTIVE
This program get elements as input and travel the tree in inorder,preorder and
postorder manner and produce the output.
ADVANTAGES
Identifying the node in the tree is easier.
Travelling the entire tree at the single time is possible.
54
SEC CSE/III DS LAB MANUAL
DISADVANTAGES
APPLICATION
ALGORITHM
Step 4: Choose the option preorder, inorder and post order to the display the elements in
the respective order.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *left,*right;
};
struct node *root;
55
SEC CSE/III DS LAB MANUAL
printf("\n %d is inserted",val);
if (opt==1)
{
printf("\tat the left\n");
getch();
}
else
{
printf("\tat the right\n");
getch();
}
}
56
SEC CSE/III DS LAB MANUAL
{
if (p!=NULL)
{
preorder(p->left);
preorder (p->right);
printf("\n %5d",p->data);
}
}
void main()
{
int op,n,root_node;
root=(struct node *)malloc(sizeof(struct node));
printf("Enter the root node:");
scanf("%d",&root_node);
root->data=root_node;
root->right=root->left=NULL;
clrscr();
do
{
printf("\n 1.Insertion");
printf("\n 2.Preorder");
printf("\n 3.Inorder");
printf("\n 4.Postorder");
printf("\n 5.Quit");
printf("\n Enter your choice\n");
scanf("%d",&op);
switch (op)
{
case 1: printf("\n Enter the element to insert\n");
scanf("%d",&n);
inser(root,n);
break;
case 2: printf("\n The preorder elements are\n");
preorder(root);
getch();
break;
case 3: printf("\n The inorder elements are\n");
inorder(root);
getch();
break;
case 4: printf("\n The postorder elements are\n");
postorder(root);
getch();
57
SEC CSE/III DS LAB MANUAL
break;
default: exit(0);
}
} while(op<5);
getch();
}
OUTPUT
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
1
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
2
30
58
SEC CSE/III DS LAB MANUAL
10
40
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
4
10
40
30
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
3
10
30
40
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
5
RESULT
Thus the expression tree has been implemented successfully in C program.
59
SEC CSE/III DS LAB MANUAL
VIVA QUESTIONS
2. What is the minimum number of nodes that a binary tree can have?
A binary tree can have a minimum of zero nodes, which occurs when the nodes have
NULL values. Furthermore, a binary tree can also have 1 or 2 nodes.
POSSIBLE QUESTIONS
60
SEC CSE/III DS LAB MANUAL
Ex no:6
Implement binary search tree
Date
DESCRIPTION
Binary Search tree is a binary tree in which the key values in the left node
is less than the root and the key value in the right node is greater than the root..
OBJECTIVE
This program get elements as input and binary search tree is constructed.
ADVANTAGES
BST is fast in insertion and deletion etc when balanced.
DISADVANTAGES
Shape of the tree depends upon order of insertion and it can be degenerated.
Searching takes long time.
61
SEC CSE/III DS LAB MANUAL
Trees offers slower insertion and deletion of elements as compared to an array.
An array is slower as compared to tree when searching for an element.
APPLICATION
Used in many search applications where data is constantly entering/leaving, such
as the map and set objects in many languages' libraries.
ALGORITHM
1. Start
2. Create a binary tree using linked representation with nodes having the structure
LEFT DATA RIGHT. Build the tree in such a way that values at each left is
less and values at each right is greater.
3. Insert: Get the value to be inserted. Create a new node and . set the data field to
X. then set the left and right links to NULL.
4. Compare X with root node data in X <root continue search in left subtree. If
X=root, then display “Duplicate data”, if X>root then search in right subtree.
Then insert the node in its right position .
5. Display: Display all the data in the tree.
6. Stop.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#define NULL 0
struct t
{
struct t*left;
struct t*right;
int data;
};
typedef struct t tree;
tree *root,*link,*node,*n,*temp,*parent;
int key;
int lm=2,rm=80,x,l=1,l2;
int i=0,j,element,c;
tree *addnode(tree*,int);
void display(tree*,int,int,int);
tree *search(tree*,int,tree**);
void delete(tree*,int);
62
SEC CSE/III DS LAB MANUAL
void main()
{
int choice;
clrscr();
while(1)
{
printf("\n \t BINARY SEARCH\n");
printf("1.Creation\n");
printf("2.Insertion\n");
printf("3.Display\n");
printf("4.Searching an element\n");
printf("5.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("\n\t\t\tBinary tree creation\n");
printf("Enter the data<0 to stop>:");
scanf("%d",&element);
link=(tree*)malloc(sizeof(tree));
link->data=element;
link->right=NULL;
link->left=NULL;
root=link;
scanf("%d",&element);
while(element!=0)
{
addnode(root,element);
scanf("%d",&element);
}
break;
case 2:printf("\nInsert the data: ");
scanf("%d",&element);
n=addnode(root,element);
break;
case 3:
clrscr();
display(root,lm,rm,l);
getch();
clrscr();
break;
case 4:
printf("\nEnter the element to be search: ");
scanf("%d",&key);
temp=search(root,key,&parent);
if(temp==root)
printf("\nThe element %d is the root. \n",temp->data);
else if(key!=temp->data)
63
SEC CSE/III DS LAB MANUAL
printf("\nThe element does not exists. \n");
else
printf("\nParent of node %d is %d. \n",temp->data,parent->data);
break;
case 5:
exit();
break;
}
getch();
}
}
64
SEC CSE/III DS LAB MANUAL
}
else
{
node->right=addnode(node->right,info);
return node;
}
}
}
}
Output:
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:1
BINARY SEARCH
1.Creation
2.Insertion
65
SEC CSE/III DS LAB MANUAL
3.Display
4.Searching an element
5.Exit
Enter your choice:3
10
6 15
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2
66
SEC CSE/III DS LAB MANUAL
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:3
10
6 15
2 11
4 13
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
67
SEC CSE/III DS LAB MANUAL
Parent of node 6 is 10.
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4
BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:5
RESULT
Thus the operations of binary search tree have been implemented successfully in C
program.
68
SEC CSE/III DS LAB MANUAL
VIVA QUESTIONS
This is a data structure question from Tree data structures. Binary Search Tree has some
special properties e.g. left nodes contains items whose value is less than root , right sub
tree contains keys with higher node value than root, and there should not be any
duplicates in the tree. Apart from definition, interview can ask you to implement binary
search tree in Java and questions on tree traversal e.g. IN order, preorder, and post order
traversals are quite popular data structure question.
POSSIBLE QUESTION
69
SEC CSE/III DS LAB MANUAL
Ex no:7
Implement insertion in AVL tree
Date
DESCRIPTION
The AVL tree involver to Declare the structure of binary search in tree.Read the
elements to be inserted into the tree. Find the place to insert the new node in the tree.Find
the balance factor for all nodes. Check it is a balanced tree (balance factor: -1, 0 , +1).
OBJECTIVE
1. struct AVLNode * buildtree ( struct AVLNode *root, int data, int *h )-building a
avl tree with nodes.
This program get elements as input and Avl tree is implemented base an the
balancing factor of the tree.
ADVANTAGES
Better search times for keys.
No case analysis.
More elegant.
DISADVANTAGES
Longer running times for the insert and remove operations.
The disadvantages the complex rotations used by the insertion and removal
algorithms needed to maintain the tree's balance.
70
SEC CSE/III DS LAB MANUAL
APPLICATION
AVL tree is that it is always balanced, guaranteeing the O(lgn) speed of the
Binary Search algorithm.
ALGORITHM
1. Start.
2. Declare the node with leftlink, rightlink, data and height of node.
3. Enter the number of elements to be inserted.
4. While inserting each element the height of each node will be checked.
5. If the height difference of left and right node is equal to . 2 for an node then
the height is unbalanced at the node.
6. The present node while inserting a new node at left sub tree then perform rotation
with left child otherwise rotation with right chile.
7. Height is unbalanced at Grand Parent node . while inserting a new node at
right subtree of parent node then perform double rotation with left.
8. Height is unbalanced at grandparent node while inserting a new node then
perform double rotation with right.
9. To view the tree perform traversal on tree.
10. Stop.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define FALSE 0
#define TRUE 1
struct AVLNode
{
int data ;
int balfact ;
struct AVLNode *left ;
struct AVLNode *right ;
};
void main( )
{
71
SEC CSE/III DS LAB MANUAL
struct AVLNode *avl = NULL ;
int h,i,num,n;
clrscr( ) ;
printf("Enter the number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&num);
avl = buildtree ( avl, num, &h ) ;
}
printf ( "\nAVL tree:\n" ) ;
display ( avl ) ;
getch( ) ;
}
72
SEC CSE/III DS LAB MANUAL
{
printf ( "\nDouble rotation, left along %d",node1 -> data ) ;
node2 = node1 -> right ;
node1 -> right = node2 -> left ;
printf ( " then right along %d.\n", root -> data ) ;
node2 -> left = node1 ;
root -> left = node2 -> right ;
node2 -> right = root ;
if ( node2 -> balfact == 1 )
root -> balfact = -1 ;
else
root -> balfact = 0 ;
if ( node2 -> balfact == -1 )
node1 -> balfact = 1 ;
else
node1 -> balfact = 0 ;
root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
break ;
case 0:
root -> balfact = 1 ;
break ;
case -1:
root -> balfact = 0 ;
*h = FALSE ;
}
}
}
case 0:
root -> balfact = -1 ;
73
SEC CSE/III DS LAB MANUAL
break;
case -1:
node1 = root -> right ;
if ( node1 -> balfact == -1 )
{
printf ( "\nLeft rotation along %d.", root -> data ) ;
root -> right = node1 -> left ;
node1 -> left = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
printf ( "\nDouble rotation, right along %d",node1 -> data ) ;
node2 = node1 -> left ;
node1 -> left = node2 -> right ;
node2 -> right = node1 ;
printf ( " then left along %d.\n", root -> data ) ;
root -> right = node2 -> left ;
node2 -> left = root ;
74
SEC CSE/III DS LAB MANUAL
root -> balfact = 0 ;
break;
case 0:
root -> balfact = -1 ;
*h = FALSE ;
break;
case -1:
node1 = root -> right ;
if ( node1 -> balfact <= 0 )
{
printf ( "\nLeft rotation along %d.", root -> data ) ;
root -> right = node1 -> left ;
node1 -> left = root ;
if ( node1 -> balfact == 0 )
{
root -> balfact = -1 ;
node1 -> balfact = 1 ;
*h = FALSE ;
}
else
{
root -> balfact = node1 -> balfact = 0 ;
}
root = node1 ;
}
else
{
printf ( "\nDouble rotation, right along %d", node1 -> data );
node2 = node1 -> left ;
node1 -> left = node2 -> right ;
node2 -> right = node1 ;
printf ( " then left along %d.\n", root -> data );
root -> right = node2 -> left ;
node2 -> left = root ;
75
SEC CSE/III DS LAB MANUAL
}
return ( root ) ;
}
case 0:
root -> balfact = 1 ;
*h = FALSE ;
break ;
case 1:
node1 = root -> left ;
if ( node1 -> balfact >= 0 )
{
printf ( "\nRight rotation along %d.", root -> data ) ;
root -> left = node1 -> right ;
node1 -> right = root ;
if ( node1 -> balfact == 0 )
{
root -> balfact = 1 ;
node1 -> balfact = -1 ;
*h = FALSE ;
}
else
{
root -> balfact = node1 -> balfact = 0 ;
}
root = node1 ;
}
else
{
printf ( "\nDouble rotation, left along %d", node1 -> data ) ;
node2 = node1 -> right ;
node1 -> right = node2 -> left ;
node2 -> left = node1 ;
printf ( " then right along %d.\n", root -> data ) ;
root -> left = node2 -> right ;
node2 -> right = root ;
76
SEC CSE/III DS LAB MANUAL
if ( node2 -> balfact == 1 )
root -> balfact = -1 ;
else
root -> balfact = 0 ;
if ( node2-> balfact == -1 )
node1 -> balfact = 1 ;
else
node1 -> balfact = 0 ;
root = node2 ;
node2 -> balfact = 0 ;
}
}
return ( root ) ;
}
Output – 1:
Output – 2:
AVL tree:
5 7 10
Output – 3:
77
SEC CSE/III DS LAB MANUAL
Enter the number of elements: 7
3214567
Output – 4:
AVL tree:
2 4 5
RESULT
Thus the insertion in AVL tree has been implemented successfully .
VIVA QUESTIONS
1.What is an AVL tree?
An AVL tree is a type of binary search tree that is always in a state of partially
balanced. The balance is measured as a difference between the heights of the subtrees
from the root. This self-balancing tree was known to be the first data structure to be
designed as such.
There are many types of sorting algorithms: quick sort, bubble sort, balloon sort,
radix sort, merge sort, etc. Not one can be considered the fastest because each algorithm
is designed for a particular data structure and data set. It would depend on the data set
that you would want to sort.
POSSIBLE QUESTIONS
1.write a program to implement Avl tree.
2. write a program to implement insertion in Avl tree.
78
SEC CSE/III DS LAB MANUAL
Ex no:8
Implement priority queue using binary heap
Date
DESCRIPTION
The AVL tree involve Declare and initialise the variable. Enter the choice
insertion, deletion and display.if the choice is insertion, then check whether the queue is
full or not. If it is not full, then insert the element in queue as ascending order.
OBJECTIVE
The main objective is to write a program to implement priority queue using binary
heap.
This program get elements as input and construct the priority queue as an output.
ADVANTAGES
The Heap sort algorithm is widely used because of its efficiency.
Heap sort works by transforming the list of items to be sorted into a heap data
structure, a binary tree with heap properties.
79
SEC CSE/III DS LAB MANUAL
DISADVANTAGES
A minor disadvantage is that the array will be 1 greater than the actual maximum
heap size if array position 0 is unused. The advantage is that this approach makes
the programming of a heap less complicated.
APPLICATION
Memory usage will depend upon whether the data already exists in memory or
whether the data is on disk. Allocating the array to be used to store the heap will be more
efficient if N, the number of records, can be known in advance. Dynamic allocation of the
array will then be possible, and this is likely to be preferable to preallocating the array
and terminating the program if this size is too small.
ALGORITHM
Step 1: Start the program.
Step 4: If the choice is insertion, then check whether the queue is full or not. If it is not
full, then insert the element in queue as ascending order.
Step 5: If the choice is deletion, then check whether the queue is empty or not. If it is not
empty, then delete the element.
Step 6: If the choice is display, then print the element in the queue.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define size 5
int rear=-1, front=-1;
int que[size];
int Qfull()
80
SEC CSE/III DS LAB MANUAL
{
if(rear==size-1)
return 1;
else
return 0;
}
void insert()
{
int item;
void priority();
printf(" Enter the elements: ");
scanf("%d",&item);
if(front==-1)
front++;
que[++rear]=item;
priority();
}
void priority()
{
int i,j,temp;
for(i=front;i<rear;i++)
for(j=front;j<rear;j++)
if(que[j]>que[j+1])
{
temp=que[j];
que[j]=que[j+1];
que[j+1]=temp;
}
}
int Qempty()
{
if((front==-1)||(front>rear))
return 1;
else
return 0;
}
void delet()
{
int item;
item=que[front];
printf(" The item deleted is %d",item);
printf("\n");
front++;
}
81
SEC CSE/III DS LAB MANUAL
void display()
{
int i;
printf(" The queue is:");
for(i=front;i<=rear;i++)
printf("\t%d",que[i]);
printf("\n");
}
void main(void)
{
int choice;
char ans;
clrscr();
front=rear=-1;
printf("\n\t\t Priority Queue\n");
do
{
printf("\n\n Main menu");
printf("\n 1.insert 2.delete 3.display");
printf("\n Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(Qfull())
printf(" Queue is full \n");
else
insert();
break;
case 2:
if(Qempty())
printf(" Cannot delete element \n");
else
delet();
break;
case 3:
if(Qempty())
printf(" Queue is empty \n");
else
display();
break;
default:
printf(" Wrong choice \n");
break;
}
printf(" Do you want to continue?");
82
SEC CSE/III DS LAB MANUAL
ans=getch();
}
while(ans=='Y'||ans=='y');
getch();
}
Output:
Priority Queue
Main menu
1.insert 2.delete 3.display
Enter your choice:1
Enter the elements: 10
Do you want to continue?
Main menu
1.insert 2.delete 3.display
Enter your choice:1
Enter the elements: 5
Do you want to continue?
Main menu
1.insert 2.delete 3.display
Enter your choice:1
Enter the elements: 20
Do you want to continue?
Main menu
1.insert 2.delete 3.display
Enter your choice:3
The queue is: 5 10 20
Do you want to continue?
Main menu
1.insert 2.delete 3.display
Enter your choice:2
The item deleted is 5
Do you want to continue?
Main menu
1.insert 2.delete 3.display
Enter your choice:3
The queue is: 10 20
Do you want to continue?
Main menu
83
SEC CSE/III DS LAB MANUAL
1.insert 2.delete 3.display
Enter your choice:1
Enter the elements: 15
Do you want to continue?
Main menu
1.insert 2.delete 3.display
Enter your choice:3
The queue is: 10 15 20
Do you want to continue?
RESULT
Thus the priority queue has been implemented successfully
VIVA QUESTIONS
1.What is the advantage of the heap over a stack?
Basically, the heap is more flexible than the stack. That’s because memory space
for the heap can be dynamically allocated and de-allocated as needed. However, memory
of the heap can at times be slower when compared to that stack.
POSSIBLE QUESTION
1.write a program to implement priority queue using binary heap.
84
SEC CSE/III DS LAB MANUAL
Ex no:9
Implement hashing with open addressing
Date
DESCRIPTION
Read the value of table size and enter the element to be stored in the hash table.
Each element is mapped into some number in the range 0 to table size – 1 and placed in
the appropriate cell using the general format of hashing function: Hash(key value) = key
value % table size.
OBJECTIVE
This program get elements as input and delivers the memory space allocated for
each value as an output.
ADVANTAGES
The main advantage of hash tables over other table data structures is speed.
This advantage is more apparent when the number of entries is large (thousands
or more). Hash tables are particularly efficient when the maximum number of
85
SEC CSE/III DS LAB MANUAL
entries can be predicted in advance, so that the bucket array can be allocated once
with the optimum size and never resized.
DISADVANTAGES
Hash tables can be more difficult to implement than self-balancing binary search
trees. Choosing an effective hash function for a specific application is more an art
than a science.
In open-addressed hash tables it is fairly easy to create a poor hash function
APPLICATION
ALGORITHM
Step 2: Read the value of table size and enter the element to be stored in the hash
table.
Step 3: Each element is mapped into some number in the range 0 to table size – 1 and
placed in the appropriate cell using the general format of hashing function:
Hash(key value) = key value % table size.
Step 4: In this method, the position of a key can be found by sequentially searching all
position starting from the position calculated by the hash function until an empty
cell is found.
Step 5: Suppose if it reaches end of the hash table, no empty cells has been found, and
then the search is continued from the beginning of the table.
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]={0,0,0,0,0,0,0,0,0,0};
int n,value,temp,hashvalue;
86
SEC CSE/III DS LAB MANUAL
clrscr();
printf("\nEnter the value of n(table size): ");
scanf("%d",&n);
do
{
printf("\nEnter the hash value: ");
scanf("%d",&value);
hashvalue=value%n;
if(a[hashvalue]==0)
{
a[hashvalue]=value;
printf("a[%d] the value %d is stored.",hashvalue,value);
}
else
{
for(hashvalue++;hashvalue<n;hashvalue++)
{
if(a[hashvalue]==0)
{
printf("Space is allocated. Give other value.");
a[hashvalue]=value;
printf("\na[%d] the value %d is stored.",hashvalue,value);
goto menu;
}
}
for(hashvalue=0;hashvalue<n;hashvalue++)
{
if(a[hashvalue]==0)
{
printf("Space is allocated.Give other value.");
a[hashvalue]=value;
printf("\na[%d] the value %d is stored.",hashvalue,value);
goto menu;
}
}
printf("ERROR!");
printf("\nEnter '0' and press Enter key twice to exit.");
}
menu:
printf("\nDo u want to enter more values (1/0): ");
scanf("%d",&temp);
}
while(temp==1);
getch();
}
87
SEC CSE/III DS LAB MANUAL
Output:
Enter the value of n(table size): 5
RESULT
Thus the hashing with open addressing has been implemented successfully.
VIVA QUESTIONS
POSSIBLE QUESTION
1.write a program to implement hashing.
2.write a program to implement hashing with open addressing
88
SEC CSE/III DS LAB MANUAL
DESCRIPTION
Enter the number of vertices. Consider any vertex in the graph. Process the vertex
and add the vertex to the tree.Find the smallest edge from the graph connecting the edge
of the vertex in the tree, such that it does not form a cycle.Add that vertex to the treeead
the value of table size and enter the element to be stored in the hash table. Each element
is mapped into some number in the range 0 to table size – 1 and placed in the appropriate
cell using the general format of hashing function: Hash(key value) = key value % table
size.
OBJECTIVE
This program get elements as input and find the minimum path of the graph as an
output.
ADVANTAGES
It's more efficient in memory usage than matrice's approach.
89
SEC CSE/III DS LAB MANUAL
Find the MST of undirected graph.
DISADVANTAGES
More complex.
APPLICATION
Prim’s Algorithm to define the operational boundaries of the System of Systems
structure. The application finds the minimum and maximum spanning trees of a
connected weighted System of Systems based on a new method.
ALGORITHM
Step 1: Start the program.
Step 3: Consider any vertex in the graph. Process the vertex and add the vertex to the
tree.
Step 4: Find the smallest edge from the graph connecting the edge of the vertex in the
tree, such that it does not form a cycle.
Step 6: Repeat step 4 until the tree contains all the vertices in the graph.
Step 7: The minimum cost of the spanning tree is found by adding the weight of the
spanning tree.
PROGRAM
#include<stdio.h>
#define MAX 10
#define TEMP 0
#define PERM 1
#define FALSE 0
#define TRUE 1
#define infinity 9999
struct node
{
int predecessor;
90
SEC CSE/III DS LAB MANUAL
int dist;
int status;
};
struct edge
{
int u;
int v;
};
void main()
{
int i, j;
int path[ MAX ];
int wt_tree, count;
struct edge tree[ MAX ];
create_graph();
printf( "Adjacency matrix is :\n" );
display();
count = maketree( tree, &wt_tree );
printf( "Weight of spanning tree is : %d\n", wt_tree );
printf( "Edges to be included in spanning tree are : \n" );
for ( i = 1;i <= count;i++ )
{
printf( "%d->", tree[ i ].u );
printf( "%d\n", tree[ i ].v );
}
}
int create_graph()
{
int i, max_edges, origin, destin, wt;
printf( "Enter number of vertices : " );
scanf( "%d", &n );
max_edges = n * ( n - 1 ) / 2;
91
SEC CSE/III DS LAB MANUAL
{
printf( "Invalid edge!\n" );
i--;
}
else
{
adj[ origin ][ destin ] = wt;
adj[ destin ][ origin ] = wt;
}
}
if ( i < n - 1 )
{
printf( "Spanning tree is not possible\n" );
exit( 1 );
}
return (0);
}
int display()
{
int i, j;
for ( i = 1;i <= n;i++ )
{
for ( j = 1;j <= n;j++ )
printf( "%3d", adj[ i ][ j ] );
printf( "\n" );
}
return(0);
}
92
SEC CSE/III DS LAB MANUAL
while ( all_perm( state ) != TRUE )
{
for ( i = 1;i <= n;i++ )
{
if ( adj[ current ][ i ] > 0 && state[ i ].status == TEMP )
{
if ( adj[ current ][ i ] < state[ i ].dist )
{
state[ i ].predecessor = current;
state[ i ].dist = adj[ current ][ i ];
}
}
}
min = infinity;
for ( i = 1;i <= n;i++ )
{
if ( state[ i ].status == TEMP && state[ i ].dist < min )
{
min = state[ i ].dist;
current = i;
}
}
state[ current ].status = PERM;
u1 = state[ current ].predecessor;
v1 = current;
count++;
tree[ count ].u = u1;
tree[ count ].v = v1;
*weight = *weight + adj[ u1 ][ v1 ];
}
return ( count );
}
93
SEC CSE/III DS LAB MANUAL
Enter weight for this edge : 5
Enter edge 4(0 0 to quit) : 4 1
Enter weight for this edge : 2
Enter edge 5(0 0 to quit) : 0 0
Adjacency matrix is :
0 1 0 2
1 0 3 0
0 3 0 5
2 0 5 0
Weight of spanning tree is : 6
Edges to be included in spanning tree are :
1->2
1->4
2->3
RESULT
Thus the Prim’s algorithm to find MST of an undirected graph has been
implemented successfully.
VIVA QUESTIONS
1.What is a graph?
A graph is one type of data structure that contains a set of ordered pairs. These
ordered pairs are also referred to as edges or arcs, and are used to connect nodes where
data can be stored and retrieved.
94
SEC CSE/III DS LAB MANUAL
Date
AIM:
To develop a program to implement Radix Sort.
ALGORITHM
4.The time complexity of the algorithm is as follows: Suppose that the n input
numbers have maximum k digits.
5.Then the Counting Sort procedure is called a total of k times. Counting Sort is a
linear, or O(n) algorithm. So the entire Radix Sort procedure takes O(kn) time.
6.If the numbers are of finite size, the algorithm runs in O(n) asymptotic time.
PROGRAM
void main()
{
int n,a[20],i;
clrscr();
printf("enter the number :");
scanf("%d",&n);
printf(" ENTER THE DATA -");
.
for(i=0;i<n;i++) com
95
SEC CSE/III DS LAB MANUAL
{
printf("%d. ",i+1);
scanf("%d",&a[i]);
}
radixsort(a,n);
.
getch(); blogspot
}
node[i].info=a[i];
node[i].next=i+1;
}
node[n-1].info=a[n-1];
node[n-1].next=-1;
first=0;
for(k=1;k<=2;k++) //consider only 2 digit number
{
for(i=0;i<10;i++)
{
front[i]=-1;
rear[i]=-1;
}
while(first!=-1)
{
p=first;
first=node[first].next;
y=node[p].info;
exp=pow(10,k-1);
j=(y/exp)%10;
q=rear[j];
if(q==-1)
front[j]=p;
else
96
SEC CSE/III DS LAB MANUAL
node[q].next=p; rear[j]=p;
} .
for(j=0;j<10&&front[j]==-1;j++)
;
first=front[j]
; while(j<=9)
{
for(i=j+1;i<10&&front[i]==-1;i++) .
;
if(i<=9)
{
p=i;
node[rear[j]].next=front[i];
}
j=i;
}
node[rear[p]].next=- . 1;
}
//copy into original array
for(i=0;i<n;i++)
{
a[i]=node[first].info;
first=node[first].next;}
clrscr();
textcolor(YELLOW);
cprintf(" DATA AFTER SORTING:");
for(i=0;i<n;i++)
printf(" %d.%d",i+1,a[i]);
}
97
SEC CSE/III DS LAB MANUAL
73
OUTPUT
9. 78
DATA AFTER SORTING: 1.4 2.12 3.34 4.43 5.55 6.76 7.78 8.90 9.98
RESULT
Thus the program has been implemented successfully.
98