0% found this document useful (0 votes)
255 views

Data Structures Lab Manual PDF

This document provides information about the Data Structures Laboratory course at Srinivasan Engineering College. It includes the syllabus, system requirements, overview of experiments, and objectives of the course. The syllabus lists 10 experiments involving implementations of common data structures like linked lists, stacks, queues, trees, and graphs. The system requirements specify the hardware as an Intel Pentium processor and the software as Turbo C. The overview explains that the aim is to develop programming skills for designing and implementing data structures and their applications. The objectives are to strengthen ability to apply suitable data structures to problems and gain practical knowledge of data structures.

Uploaded by

abhiraj1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views

Data Structures Lab Manual PDF

This document provides information about the Data Structures Laboratory course at Srinivasan Engineering College. It includes the syllabus, system requirements, overview of experiments, and objectives of the course. The syllabus lists 10 experiments involving implementations of common data structures like linked lists, stacks, queues, trees, and graphs. The system requirements specify the hardware as an Intel Pentium processor and the software as Turbo C. The overview explains that the aim is to develop programming skills for designing and implementing data structures and their applications. The objectives are to strengthen ability to apply suitable data structures to problems and gain practical knowledge of data structures.

Uploaded by

abhiraj1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

SEC CSE/III DS LAB MANUAL

SRINIVASAN ENGINEERING COLLEGE


COMPUTER SCIENCE AND ENGINEERING
ANNA UNIVERSITY -CHENNAI
REGULATION 2008
II CSE (2013-2014)

CS2208 DATA STRUCTURES LABORATORY


LAB MANUAL

PREPARED BY

K.VINOTHINI, Assistant Professor.

1
SEC CSE/III DS LAB MANUAL

PREFACE

This laboratory manual is prepared by the Department of Computer Science and

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

Dr.B.Karthikeyan, for his valuable information and guidance, which helped me in

completing this task through various stages.

We extend our hearty thanks to our head of the department Ms.S.Jayanthi for her

constant encouragement and constructive comments.

Finally the valuable comments from fellow faculty and assistance provided by

the department are highly acknowledged. We would like to thank everyone who helped

us at various stages in completing this work.

Last but not least we express our heartfelt thanks to Lord Almighty for being

there when we needed him most always.

3
SEC CSE/III DS LAB MANUAL

TABLE OF CONTENTS

CHAPTER NO . TITLE PAGE NO.


1 INTRODUCTION TO THE LANGUAGE 5
2 SYLLABUS 7
3 SYSTEM REQUIREMENTS 8
1 Hardware Requirements
2 Software Requirements
4 ABOUT EACH EXPERIMENT 9
1. Aim
2. Description About Each Experiment
3. Learning Objective
4. General procedure to execute programs
5 LIST OF EXPERIMENTS
1a.Implement singly linked lists. 10
1b.Implement doubly linked lists. 18
2.Represent a polynomial as a linked list and write 28
functions for polynomial addition.
3.Implement stack and use it to convert infix to
postfix expression 36
4.Implement a double-ended queue (dequeue)
where insertion and deletion operations are
possible at both the ends. 43
5.Implement an expression tree.Procedure its pre- 54
order, in-order, and postorder traversals.
6.Implement binary search tree 61
7.Implement insertion in AVL trees. 70
8.Implement priority queue using binary heaps. 79
9.Implement hasing with open addressing. 85
10.Implement prim’s algorithm using priority queue 89
to find MST of an Undirected graph.
6 EXPERIMENTS BEYOND THE SYLLABUS
1.Implement Radix Sort 95

REFERENCES

4
SEC CSE/III DS LAB MANUAL

CHAPTER 1

INTRODUCTION OF THE LANGUAGE (CORRESPONDING VERSION)

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.

of a problem in terms of function modules or blocks.


ten in C are efficient and fast. This is due to its variety of data types
andpowerful operators. It is many times faster than BASIC.

acollection of functions, which are supported by the C library.

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.

ed simply, this means


that the code is compacted into executable instruction (in the case of windows anyway)
rather than being "translated" on the fly at run time.

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

embedded software/firmware for various electronics, industrial and communications


products which use micro-controllers.

applications and hardware products.

operating systems to spreadsheets to expert systems.

make-up the operating system.


-purpose language because of its popularity with
programmers.

6
SEC CSE/III DS LAB MANUAL

CHAPTER 2

SYLLABUS

CS2208-DATA STRUCTURES LABORATORY


LIST OF EXPERIMENTS

1.Implement singly and doubly linked lists.

2.Represent a polynomial as a linked list and write functions for polynomial addition.

3.Implement stack and use it to convert infix to postfix expression

4.Implement a double-ended queue (dequeue) where insertion and deletion operations are

possible at both the ends.

5.Implement an expression tree.Produce its pre-order, in-order, and postorder traversals.

6.Implement binary search tree.

7.Implement insertion in AVL trees.

8.Implement priority queue using binary heaps.

9.Implement hasing with open addressing.

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:

Intel Pentium 915 GV


80GB SATA II
512MB DDR

2 SOFTWARE REQUIREMENTS:

TURBO C

8
SEC CSE/III DS LAB MANUAL

CHAPTER 4
ABOUT THE DATA STRUCTURES LABORATORY

AIM

The aim of the Data Structures Laboratory is to develop a students programming


skills in design and implement of data structures and their applications.

LEARNING OBJECTIVE

The objective of the course is to develop skills to design and analyze


simple linear and non linear data structures and to Strengthen the ability to identify and
apply the suitable data structure for the given real world problem and also to Gain
knowledge in practical applications of data structures .
To become proficient with the fundamental tools of program design using structur
ed
problem solving, data representation, software engineering principles and comparative an
alysis
of algorithms.To develop the ability to design and write programs for implementation of
such algorithms.

9
SEC CSE/III DS LAB MANUAL

Implement singly linked list.


Ex no:1a

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:

a) The insertion operation


(i) At the front of the list
(ii) At the back of the list
(iii) At any position in the list
b) Deleting a node.If the specified node is not present in the list an error message
should be displayed. Both the options must be demonstrated.
c) Searching a node based on and update the information content. If the specified
node is not present in the list an error message should be displayed. Both the options
must be demonstrated. Displaying all nodes in the list.

OBJECTIVE
The main objective is to write program to implement singly linked list
which can create and insert a element with a single link.

SYNTAXES AND KEYWORDS

insertbef()-Insert the node/element in the list

delnode()-Delete the node from the list if available, otherwise display error message

display()-Display all the nodes available in the list.

REQUIREMENTS FOR EXECUTION

S.No Facilities required quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

10
SEC CSE/III DS LAB MANUAL

EXPECTED OUTPUT AND ITS FORM

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.

 Insertion and deletion of values is easier as compared to array, as no shifting of


values is involved.

 Dynamic structure (Mem. Allocated at run-time).

 We can have more than one datatype.

 Re-arrange of linked list is easy (Insertion-Deletion).

 It doesn’t waste memory.

LIMITATIONS

 Nodes can only be accessed sequentially. That means, we cannot jump to a


particular node directly.

 Because of the above disadvantage, binary search algorithm cannot be


implemented on the Singly linked list.

 There is no way to go back from one node to previous one. Only forward
traversal is possible.

APPLICATIONS

 A primary advantage to a linked list as opposed to a vector is that random-


insertion time is as simple as decoupling a pair of pointers and recoupling them to
the new object (this is of course, slightly more work for a doubly-linked list).

 A vector, on the other hand generally reorganizes memory space on insertions,


causing it to be significantly slower.

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

SINGLY LINKED LIST

1.CREATE
2.INSERT
3.DELETE
4.EXIT

ENTER YOUR CHOICE : 1

ENTER THE DATA: 10

10

1.CREATE
2.INSERT
3.DELETE
4.EXIT

ENTER YOUR CHOICE : 2

ENTER THE DATA: 20

15
SEC CSE/III DS LAB MANUAL
ENTER THE POSITION: 2

10
20

1.CREATE
2.INSERT
3.DELETE
4.EXIT

ENTER YOUR CHOICE : 2

ENTER THE DATA: 30

ENTER THE POSITION: 3

10
20
30

1.CREATE
2.INSERT
3.DELETE
4.EXIT

ENTER YOUR CHOICE : 3

ENTER THE POSITION : 2

DELETED ELEMENT IS 20

10
30

1.CREATE
2.INSERT
3.DELETE
4.EXIT

ENTER YOUR CHOICE : 4

RESULT

Thus the program has been successfully executed by implementing a singly a


linked and produced output as shown above.

16
SEC CSE/III DS LAB MANUAL
VIVA QUESTIONS

1.What is Linked List?

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.

2.What is Singly Linked List?

It has only head part and corresponding references to the next nodes.

3. How would you sort a linked list?

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.

4. Whether Linked List is linear or Non-linear data structure?

`According to Access strategies Linked list is a linear one. According to Storage Linked
List is a Non-linear one.

POSSIBLE QUESTIONS

1.Implement a singly linked list-Insert node and the end.

2. Implement a singly linked list-Delete the inbetween node.

3.Implement a singly linked list-By displaying all nodes present in the list.

17
SEC CSE/III DS LAB MANUAL

Implement Doubly linked list.


Ex no:1b

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.

SYNTAXES AND KEYWORDS

1.A generic doubly linked list node can be designed as:

typedef struct
node {
void* data;
struct node* next;
struct node*
prev;
} node;

18
SEC CSE/III DS LAB MANUAL

2. newnode=(node *)malloc(sizeof(node))-Insert the new node in the list

REQUIREMENTS FOR EXECUTION

S.No Facilities required quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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

node *create(node **lastnode)

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

void display(node *first,node *last)


{
printf("\n Forward traversal\n");
while(first!=NULL)
{
printf("%d\t",first->item);
first=first->right;
}
printf("\n Backward traversal\n");
while(last!=NULL)
{
printf("%d\t",last->item);
last=last->left;
}
return;
}

void insert(node **first,node **last)


{

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

void del(node **first,node **last)


{

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:

DOUBLY LINKED LIST


******************
Main menu
1.Create
2.Insert
3.Delete
4.Display

24
SEC CSE/III DS LAB MANUAL
5.Exit
Enter your choice:1

Enter the data(0 to stop):


10
20
0

Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:2

New data item:30

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

New data item:40

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

Enter the data to be deleted:40

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

1.Define Doubly Linked List

It is a collection of data elements called nodes, where each node is divided into three
parts

 An info field that contains the information stored in the node.


 Left field that contain pointer to node on left side.
 Right field that contain pointer to node on right side.
2.What is difference between Singly Linked List and Doubly Linked List data
structure?

This is another classical interview question on data structure, mostly asked on


telephonic rounds. Main difference between singly linked list and doubly linked list is
ability to traverse. In a single linked list, node only points towards next node, and there is
no pointer to previous node, which means you can not traverse back on a singly linked
list. On the other hand doubly linked list maintains two pointers, towards next and
previous node, which allows you to navigate in both direction in any linked list.

3. What is the primary advantage of a linked list?

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

1.Write a program to implement doubly linked list-insert a node


2.Write a program to implement doubly linked list-delete a node from the list if
present,other wise display error message.

27
SEC CSE/III DS LAB MANUAL

Represent a polynomial as a linked linked lists and write


Ex no:2 functions for polynomial addition

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.

SYNTAXES AND KEYWORDS


1. polyaddtion()-polynomial addition of two variales
2. sorting()-variables are arranged in a particular order.
3. REQUIREMENTS FOR EXECUTION

S.No Facilities required quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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.

 No prior estimation on number of terms in the polynomial is required.This result


is flexible and more space efficient representation.

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.

 A polynomial is represented with various terms containing coefficients and


exponents.
ALGORITHM
1. Start.
2. Create a Linked lists used to represent and manipulate polynomials.

3. A polynomial can be represented as

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

Coefficient Field - Which holds the coefficient of a term


Exponent Field - Which holds the exponent value of that term
Link Field - Address of the next term in the polynomial
.
eeeexclusive
5. P and Q are two polynomials.P & Q can be represented as linked list.
6. P:5x2+6x+7

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

printf("\nThe second sorted list is :");


ptr=start2;
sorting();
ptr=start2;
display();
printf("\nThe sum of the two lists are :");
polyaddtion();
ptr=start3;
display();
getch();
}

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:

Enter the elements of the first polynomial :


Enter the coff and pow :10 3

33
SEC CSE/III DS LAB MANUAL

Do u want enter more coff ?(y/n) :y

Enter the coff and pow :20 2

Do u want enter more coff ?(y/n) :y

Enter the coff and pow :30 1

Do u want enter more coff ?(y/n) :y

Enter the coff and pow :5 0

Enter the elements of the second polynomial :


Enter the coff and pow :30 3

Do u want enter more coff ?(y/n) :y

Enter the coff and pow :20 2

Do u want enter more coff ?(y/n) :y

Enter the coff and pow :10 1

Do u want enter more coff ?(y/n) :y

Enter the coff and pow :5 0

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.

2.Which Data structure is easier to represent a polynomial operation?

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

Ex no:3 Implement Stack and use it to convert infix to postfix expression

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

SYNTAXES AND KEYWORDS

1. infixtopostfix(void)-convert the expression from infix to postfix.


2. push(char sym)-character is puhed from the stack.

REQUIREMENTS FOR EXECUTION

S.No Facilities required quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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

 There is a limitation in storing the items into the stack.

 Insertion and deletion operations in a stack using an array involves more data
movements.

APPLICATIONS OF STACK
 Infix to postfix conversion.

 Evaluation of arithmetic expressions.

 Decimal to binary conversion.

ALGORITHM
1.Start the program.
2 .The expression is to be read from left to right.

3. If the input symbol read is an ‘(‘then push it into the stack.

4. If the input symbol read is an operand then place it in postfix expression.

5.If the input symbol read is an operator then


5.1.Check the precedence of the operator in the stack which is in the stack
has greater precedence than the precedence of the operator read, if so then remove
that symbol from the stack and place in the postfix expression.
Repeat the step 5.1 till the operator in the stack has greater precedence than the
operator being read.
5.2: Otherwise push the operator being read onto the stack.

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.

8.Finally print the postfix expression.

9. End of the program.

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

static char infix[N+1],stack[N],postfix[N+1];


static int top;

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

int gettype(char sym)


{
switch(sym)
{
case '(':
return(LP);
case ')':
return(RP);
case '+':
case '-':
case '*':
case '/':
case '%':
return(OPERATOR);
default :
return(OPERAND);
}
}

void push(char sym)


{
if(top>N)
{
printf("\nStack is full\n");
exit(0);
}
else
stack[++top]=sym;
}

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

Enter an infix expression


a*b+c*d/e

infix = a*b+c*d/e
post fix =ab*cd*e/+

Do you wish to continue(y/n):y


Enter an infix expression
a+b

infix = a+b
post fix =ab+

Do you wish to continue(y/n):n

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.

4.What is a postfix expression?


A postfix expression is an expression in which each operator follows its operands.
The advantage of this form is that there is no need to group sub-expressions in
parentheses or to consider operator precedence.

POSSIBLE QUESTIONS

1.write a program to implement a stack.

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

Implement a double-ended queue (dequeue) where


Ex no:4 insertion and deletion operations are possible at both the
ends.
Date

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

The main objective is to write a program to Implement a double-ended


queue (dequeue) where insertion and deletion operations are possible at both the
ends.

SYNTAXES AND KEYWORDS

1. insert_right()-inserting of elemnt at the right side of the queue.


2. delete_right-Deleting element from the queue.

REQUIREMENTS FOR EXECUTION

S.No Facilities required quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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.

 Insertion and Deletion operation is easier in case of double-ended queue.

DISADVANTAGES

 Deletion is difficult compare to a normal queue

APPLICATION

 Batch processing in an operating System.


 To implement Priority queue. Priority queues can be used to sort the elements
using Heap Sort.
 Simulation.
 Computer Networks where the server takes the jobs of the client as per the queue
strategy.

ALGORITHM

Step 1: Start the program.

Step 2: Declare and initialise the variable.

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.

Step 6: End of the program.

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:

1.Input restricted dequeue


2.Output restricted dequeue
Enter your choice : 1
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 : 10
1.Insert at right
2.Delete from left

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.

3.What is an ordered list?


An ordered list is a list in which each node’s position in the list is determined by
the value of its key component, so that the key values form an increasing sequence, as the
list is traversed.

4.What is the difference between a PUSH and a POP?


Pushing and popping applies to the way data is stored and retrieved in a stack. A
push denotes data being added to it, meaning data is being “pushed” into the stack. On
the other hand, a pop denotes data retrieval, and in particular refers to the topmost data
being accessed.

POSSIBLE QUESTION

1.Write a program to implement a double ended queue


2.write a program to implement a queue where insertion and deletion possible at both the
ends of the queue.

53
SEC CSE/III DS LAB MANUAL

Ex no:5 Implement an expression tree. Produce its pre-order, in-order,


and postorder traversals
Date

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

The main objective is to write a program to implement an expression tree.


Produce its pre-order, in-order, and postorder traversals

SYNTAXES AND KEYWORDS

1. inorder(struct node *p)-travel the tree in inorder way.

2. postorder(struct node *p)- travel the tree in postorder way.

3. preorder(struct node *p)- travel the tree in preorder way

REQUIREMENTS FOR EXECUTION

S.No Facilities required quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3
EXPECTED OUTPUT AND ITS FORM

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

 Inserting of node is difficult.


 Deleting a node from existing tree is difficult.

APPLICATION

It is used to print the sorted numbers from a Binary Search Tree.

ALGORITHM

Step 1: Start the program.

Step 2: Enter the value of root node.

Step 3: Choose the option insertion, to insert the elements.

Step 4: Choose the option preorder, inorder and post order to the display the elements in
the respective order.

Step 5: End of the program.

PROGRAM

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

struct node
{
int data;
struct node *left,*right;
};
struct node *root;

void ins(struct node *n,int val,int opt)


{
struct node *t;
t=(struct node *)malloc(sizeof(struct node));
t->data=val;
t->right=t->left=NULL;
if (opt==1)
n->left=t;
else
n->right=t;

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

void inser(struct node *t,int x)


{
if (t->data >x)
if (t->left==NULL)
ins(t,x,1);
else
inser(t->left,x);
else if (t->data < x)
if (t->right==NULL)
ins(t,x,2);
else
inser(t->right,x);
else
printf("\n Element is already present in the list\n");
}

void inorder(struct node *p)


{
if (p!=NULL)
{
inorder(p->left);
printf("\n %5d",p->data);
inorder (p->right);
}
}

void preorder(struct node *p)


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

56
SEC CSE/III DS LAB MANUAL

void postorder(struct node *p)

{
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

Enter the root node:30


1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
1

Enter the element to insert


10

10 is inserted at the left

1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
1

Enter the element to insert


40

40 is inserted at the right

1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
2

The preorder elements are

30

58
SEC CSE/III DS LAB MANUAL
10
40
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
4

The postorder elements are

10
40
30
1.Insertion
2.Preorder
3.Inorder
4.Postorder
5.Quit
Enter your choice
3

The inorder elements are

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

1.How do signed and unsigned numbers affect memory?


In the case of signed numbers, the first bit is used to indicate whether positive or
negative, which leaves you with one bit short. With unsigned numbers, you have all bits
available for that number. The effect is best seen in the number range (unsigned 8 bit
number has a range 0-255, while 8-bit signed number has a range -128 to +127.

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.

3.What are dynamic data structures?


Dynamic data structures are structures that expand and contract as a program runs. It
provides a flexible means of manipulating data because it can adjust according to the size
of the data.

POSSIBLE QUESTIONS

1.write a program to implement expression tree.

2.write a program to implement a tree traversal.

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

The main objective is to write a program implement binary search tree.

SYNTAXES AND KEYWORDS

1. tree *addnode(tree *node,int info)-nodes can be added to the tree.

2. tree *search(tree *root,int key,tree **parent)-search the node in the tree.

REQUIREMENTS FOR EXECUTION

S.No Facilities required Quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3
EXPECTED OUTPUT AND ITS FORM

This program get elements as input and binary search tree is constructed.

ADVANTAGES
 BST is fast in insertion and deletion etc when balanced.

 Very efficient and its code is easier than link lists.

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

void display(tree *t,int lm,int rm,int l)


{
if(t!=NULL)
{
x=(lm+rm)/2;
gotoxy(x,4*l);
printf("%d\n\n",t->data);
gotoxy(35, 25);
display(t->left,lm,x+l2,l+1);
display(t->right,x-4,rm,l+1);
}
}

tree *addnode(tree *node,int info)


{
if(node==NULL)
{
node=(tree*)malloc(sizeof(tree));
node->data=info;
node->left=NULL;
node->right=NULL;
return node;
}
else
{
if(node->data==info)
{
printf("\nData already exists. \n");
return node;
}
else
{
if(node->data>info)
{
node->left=addnode(node->left,info);
return node;

64
SEC CSE/III DS LAB MANUAL
}
else
{
node->right=addnode(node->right,info);
return node;
}
}
}
}

tree *search(tree *root,int key,tree **parent)


{
tree *temp;
temp=root;
while(temp!=NULL)
{
if(temp->data==key)
{
printf("\nThe element %d is present \n",temp->data);
return temp;
}
*parent=temp;
if(temp->data>key)
temp=temp->left;
else
temp=temp->right;
}
return NULL;
}

Output:

BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:1

Binary tree creation


Enter the data<0 to stop>:10 6 15 2 0

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

Insert the data: 4

BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2

Insert the data: 11

BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:2

Insert the data: 13

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

Insert the data: 2

Data already exists.

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

Enter the element to be search: 11

The element 11 is present

Parent of node 11 is 15.

BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4

Enter the element to be search: 6

The element 6 is present

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

Enter the element to be search: 10

The element 10 is present

The element 10 is the root.

BINARY SEARCH
1.Creation
2.Insertion
3.Display
4.Searching an element
5.Exit
Enter your choice:4

Enter the element to be search: 40

The element does not exists.

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

1.What is binary search tree?

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.

2.What is a linear search?


A linear search refers to the way a target key is being searched in a sequential data
structure. Using this method, each element in the list is checked and compared against the
target key, and is repeated until found or if the end of the list has been reached.

POSSIBLE QUESTION

1.write a programto implement binary search tree.

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

The main objective is to write a program to implement insertion in avl tree.

SYNTAXES AND KEYWORDS

1. struct AVLNode * buildtree ( struct AVLNode *root, int data, int *h )-building a
avl tree with nodes.

REQUIREMENTS FOR EXECUTION

S.No Facilities required Quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3
EXPECTED OUTPUT AND ITS FORM

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

struct AVLNode * buildtree ( struct AVLNode *, int, int * ) ;


struct AVLNode * balright ( struct AVLNode *, int * ) ;
struct AVLNode * balleft ( struct AVLNode *, int * ) ;
void display ( struct AVLNode * ) ;

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

struct AVLNode * buildtree ( struct AVLNode *root, int data, int *h )


{
struct AVLNode *node1, *node2 ;
if ( !root )
{
root = ( struct AVLNode * ) malloc ( sizeof ( struct AVLNode ) ) ;
root -> data = data ;
root -> left = NULL ;
root -> right = NULL ;
root -> balfact = 0 ;
*h = TRUE ;
return ( root ) ;
}

if ( data < root -> data )


{
root -> left = buildtree ( root -> left, data, h ) ;
/* If left subtree is higher */
if ( *h )
{
switch ( root -> balfact )
{
case 1:
node1 = root -> left ;
if ( node1 -> balfact == 1 )
{
printf ( "\nRight rotation along %d.", root -> data ) ;
root -> left = node1 -> right ;
node1 -> right = root ;
root -> balfact = 0 ;
root = node1 ;
}
else

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

if ( data > root -> data )


{
root -> right = buildtree ( root -> right, data, h ) ;
/* If the right subtree is higher */
if ( *h )
{
switch ( root -> balfact )
{
case 1:
root -> balfact = 0 ;
*h = FALSE ;
break ;

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 ;

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 ;
}
}
}
return ( root ) ;
}

/* balances the tree, if right sub-tree is higher */


struct AVLNode * balright ( struct AVLNode *root, int *h )
{
struct AVLNode *node1, *node2 ;
switch ( root -> balfact )
{
case 1:

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 ;

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

75
SEC CSE/III DS LAB MANUAL
}
return ( root ) ;
}

/* balances the tree, if left sub-tree is higher */


struct AVLNode * balleft ( struct AVLNode *root, int *h )
{
struct AVLNode *node1, *node2 ;
switch ( root -> balfact )
{
case -1:
root -> balfact = 0 ;
break ;

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

/* displays the tree in-order */


void display ( struct AVLNode *root )
{
if ( root != NULL )
{
display ( root -> left ) ;
printf ( "%d\t", root -> data ) ;
display ( root -> right ) ;
}
}

Output – 1:

Enter the number of elements: 5


21457

Left rotation along 4.


AVL tree:
1 2 4 5 7

Output – 2:

Enter the number of elements: 3


5 10 7

Double rotation, right along 10 then left along 5.

AVL tree:
5 7 10

Output – 3:

77
SEC CSE/III DS LAB MANUAL
Enter the number of elements: 7
3214567

Right rotation along 3.


Left rotation along 3.
Left rotation along 2.
Left rotation along 5.
AVL tree:
1 2 3 4 5 6 7

Output – 4:

Enter the number of elements: 3


524

Double rotation, left along 2 then right along 5.

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.

2.What is the balancing factor for AVL tree?


The balancing factor is -1,0,+1.

3.Which sorting algorithm is considered the fastest?

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.

SYNTAXES AND KEYWORDS

1. priority()-priorities the node.

2. insert()-inserting the node.

REQUIREMENTS FOR EXECUTION

S.No Facilities required Quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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

 The main disadvantage of using an array, as opposed to a dynamically allocated


tree, to implement a heap is that a maximum size needs to be specified based on
the allocation of the array.

 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 2: Declare and initialise the variable.

Step 3: Enter the choice insertion, deletion and display.

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.

Step 7: End of the program.

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

The main objective is to write a program to implement hashing with open


addressing.

SYNTAXES AND KEYWORDS

1. hashvalue=value%n-the hash value is maintained to insert value in table.

REQUIREMENTS FOR EXECUTION

S.No Facilities required Quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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

 Search documents on the web for documents similar to a given one.


 Determine whether a new document belongs in one set or another.

ALGORITHM

Step 1: Start the program.

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.

Step 6: End of the program

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

Enter the hash value: 21


a[1] the value 21 is stored.
Do u want to enter more values (1/0): 1

Enter the hash value: 23


a[3] the value 23 is stored.
Do u want to enter more values (1/0): 1

Enter the hash value: 25


a[0] the value 25 is stored.
Do u want to enter more values (1/0): 1

Enter the hash value: 40


Space is allocated. Give other value.
a[2] the value 40 is stored.
Do u want to enter more values (1/0): 1

Enter the hash value: 52


Space is allocated. Give other value.
a[4] the value 52 is stored.
Do u want to enter more values (1/0): 1

Enter the hash value: 45


ERROR!
Enter '0' and press Enter key twice to exit.
Do u want to enter more values (1/0): 0

RESULT
Thus the hashing with open addressing has been implemented successfully.

VIVA QUESTIONS

1.What is a bubble sort and how do you perform it?


A bubble sort is one sorting technique that can be applied to data structures such
as an array. It works by comparing adjacent elements and exchanges their values if they
are out of order. This method lets the smaller values “bubble” to the top of the list, while
the larger value sinks to the bottom.

2.What are the parts of a linked list?


A linked list typically has two parts: the head and the tail. Between the head and
tail lie the actual nodes, with each node being linked in a sequential manner.

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

Ex no:10 Implement prim’s algorithm using priority queue to find MST


of an Undirected graph.
Date

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

The main objective is to write a program to implement prim’s algorithm using


priority queue to find MST of an Undirected graph.

SYNTAXES AND KEYWORDS

1. create_graph()-used to create graph.

REQUIREMENTS FOR EXECUTION

S.No Facilities required Quantity


1 System 1
2 o/s Windows xp/2000
3 s/w TURBO C3

EXPECTED OUTPUT AND ITS FORM

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.

 Use more memory.

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 2: Enter the number of vertices.

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 5: Add that vertex to the tree.

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.

Step 8: End of the program.

PROGRAM

// Implementation of Prim’s algorithm

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

int adj[ MAX ][ MAX ];


int n;

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;

for ( i = 1;i <= max_edges;i++ )


{
printf( "Enter edge %d(0 0 to quit) : ", i );
scanf( "%d %d", &origin, &destin );
if ( ( origin == 0 ) && ( destin == 0 ) )
break;
printf( "Enter weight for this edge : " );
scanf( "%d", &wt );
if ( origin > n || destin > n || origin <= 0 || destin <= 0 )

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

int maketree( struct edge tree[ MAX ], int *weight )


{
struct node state[ MAX ];
int i, k, min, count, current, newdist;
int m;
int u1, v1;
*weight = 0;
for ( i = 1;i <= n;i++ )
{
state[ i ].predecessor = 0;
state[ i ].dist = infinity;
state[ i ].status = TEMP;
}
state[ 1 ].predecessor = 0;
state[ 1 ].dist = 0;
state[ 1 ].status = PERM;
current = 1;
count = 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 );
}

int all_perm( struct node state[ MAX ] )


{
int i;
for ( i = 1;i <= n;i++ )
if ( state[ i ].status == TEMP )
return FALSE;
return TRUE;
}
Output:
Enter number of vertices : 4
Enter edge 1(0 0 to quit) : 1 2
Enter weight for this edge : 1
Enter edge 2(0 0 to quit) : 2 3
Enter weight for this edge : 3
Enter edge 3(0 0 to quit) : 3 4

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.

2.What is Huffman’s algorithm?


Huffman’s algorithm is associated in creating extended binary trees that has
minimum weighted path lengths from the given weights. It makes use of a table that
contains frequency of occurrence for each data element.
3.What is Fibonacci search?
Fibonacci search is a search algorithm that applies to a sorted array. It makes use
of a divide-and-conquer approach that can greatly reduce the time needed in order to
reach the target element.
4.Briefly explain recursive algorithm.
Recursive algorithm targets a problem by dividing it into smaller, manageable
sub-problems. The output of one recursion after processing one sub-problem becomes the
input to the next recursive process.
POSSIBLE QUESTIONS
1.write a program to implement prim’s algorithm.
2.write a program to find the MST of an undirected graph.

94
SEC CSE/III DS LAB MANUAL

BEYOND THE SYLLABUS

Implement Radix Sort


Ex no:11

Date

AIM:
To develop a program to implement Radix Sort.

ALGORITHM

1.Radix sort is one of the linear sorting algorithms for integers.


2. It functions by sorting the input numbers on each digit, for each of the digits in
the numbers.
3.However, the process adopted by this sort method is somewhat counterintuitive,
in the sense that the numbers are sorted on the least-significant digit first,
followed by the second-least significant digit and so on till the most significant
digit.

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

#define NUMELTS 100


# include<stdio.h>
#include<conio.h>
#include<math.h>
void radixsort(int a[],int);

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
}

void radixsort(int a[],int n)


{
int rear[10],front[10],first,p,q,exp,k,i,y,j;
Struct
{
int info;
.
eeeexclusive
int next;
}node[NUMELTS];
for(i=0;i<n-1;i++)
{

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

enter the number :9

ENTER THE DATA -1. 90


2. 76
3. 12
4. 34
5. 98
6. 55
7. 43
8. 4

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

You might also like