You are on page 1of 61

Abstract Data Type (ADT) and Data Structure .....................................................

2
Linked Lists ...................................................................................................................... 4
Introduction.................................................................................................................. 4
Program for Singly Linked List ............................................................................. 11
Doubly linked lists ........................................................................................................ 16
Program For Doubly Linked List .......................................................................... 21
Circular Lists .................................................................................................................. 25
Program for Circular Singly Linked List ............................................................. 30
Stacks and Queues ...................................................................................................... 35
Program for Stack Using Linked List .................................................................. 40
Trees ................................................................................................................................ 44
Definition of trees..................................................................................................... 45
Binary tree .................................................................................................................. 47
Representation of a Binary Tree using pointer ............................................... 50
Binary tree traversal ............................................................................................... 51
Binary search Tree ................................................................................................... 53

www.gtuking.blogspot.com
Abstract Data Type (ADT) and Data Structure

“type” or “data type” is common terminology in mathematics and in


programming languages. Variables are declared to be of a particular “data type”. These
declarations mean that the values only from a particular set. The type of the variable
determines this set. “type” may be defined as a set of values. ( However , this
definition is not complete as will be seen in the sequel). There are plenty of examples of
“data type” in programming languages. In languages like FORTRAN, Pascal , C ,the
standard built-in types include integers, real numbers ,characters , and so on. Variables
declared of type integer may assume any integral value.

However, depending on the machine, there is limit to the range of integer that
can be properly used in any programming language. Hence, there is a subtle distinction
between “type” in mathematics and “type” in computers. For example, the type “integer”
is definitely a finite set in any programming language. This distinction is more
pronounced for real numbers. Since each number is to be finally represented in finite
number of bits in a computer, the continuity property of real numbers in mathematics is
lost the corresponding type in a programming language. In fact the set of real numbers
in mathematics does not have a one to one mapping to the set of real numbers in a
programming language.

Moreover, a type is not just a set of values. A “type” also determines the set of
operations applicable to the set of values that the said “type” represents. Note that the
operations are defined while “type” itself is being defined. In other word, to define a
type, the set of values and the set operations are defined.

Any object of that type can assume the values defined for that type and the
operations defined on that type might be applied on the object of that type. Thus, for
type “integer”, the operations such as addition, subtraction, multiplication etc. are
defined. These operations are defined to be binary and they are defined on two objects
of type integers. So, two variables of type integer can be added. But, two variables of
type character cannot be added. But two variables of type character cannot be, usually,
added of multiplied. Although most programming languages support some standard
“data type”, they are not enough for most of the applications. So, programming
languages usually support creating new data types in terms of “ Structured types”. A “
structured type” is made up of several components each of which is either an atomic
type or anther “ Structured type “. This can be accomplished in “C” language by defining
a “struct”. However, just by defining a structured type, the operations applicable to
objects of that type can be specified. This is why the concept of an Abstract data Type
(ADT) is required.

An ADT is defined to be a mathematical model of a user-defined type along with a


collection of all primitive operations on that model. To illustrate this motion, define a new
data type “SET”, which denotes a set of entities. An object of type “SET” is defined to be
a collection of “N” otherwise unrelated entities. If the type of each entity is represented
by a set of values “D” then an object of type “SET” having “n” entities may assume any
value from the set D (i.e. D X D X D X …….XD) where multiplication in this context means
set multiplication. The primitive operations that may be defined for this ADT are given in
the following:

www.gtuking.blogspot.com
1. Assign (SET A, SET B)
This operation assigns the set identified by “B” to “A”.
2. Null (SET A)
This operation assigns null (an empty set) to “A”.
3. SET Union (SET A, SET B)
These operation cerates a new set, which is the “union” of the sets, identified by
“A” and “B”. This operation returns the new set.
4. int Find (ENTITY x, SET A)
This operation searches the set “A” to check whether an entity “x” is a member of
the set “A”.
If “x” is a member of the set “A” then the operation returns a value “1”; otherwise
the operation returns a value “0”.
5. SET Intersection (SET A, SET B)
This procedure returns a new set which is the intersection of the sets identified by
“A” and “B”.
6. int Cardinality (SET A) this operation returns an integer, which is the number in the
set identified by “A”.

www.gtuking.blogspot.com
Linked Lists

Introduction

Array data structure has simple and beautiful characteristics. It is simple to


understand; time to access any element from an array is constant. But some severe
limitations can also be attributed to its simple structure. First, the size of an array has to
be defined when the program is being written and its space reserved during compilation
of the program. This means that the programmer has to decide on the maximum size of
data, which is expected and accordingly define the size of the array. During execution of
the program, it may so happen that the actual size is less than the defined size and so,
good amount of space is wasted. The opposite phenomenon could also happen. While
executing whit larger sample, the size of actual data may potentially exceed the limits of
the defined size producing undesirable results. More annoying is the fact that such
“overflow” occurred not because of unavailability of memory in the computing system but
because the array was defined to be too small. Even when one array is defined large
enough, overflow can still happen. This is because, different lists grow and shrink during
execution of a program and overflow any occur for one array while the space of other
arrays may remain relatively unused.

The second problem that arises in list implementation using arrays is that of
insertions and deletions. It has been mentioned that during insertion operation, the
modes after the inserted node have to be shifted one position to the right. Similarly,
during deletion, all nodes to the right of the deleted node have to be shifted to left. This
means that number of shifting for insertion and deletion is O (n) for a list of “n” nodes in
the average case. If individual elements of an array are huge records then such shifting
will actually become prohibitively time-consuming. In this chapter, a new data structure
is discussed in which these shortcomings are overcome.

An elegant solution to the problem to the problem of data movements whit occurs in
arrays can be achieved through “linked” representation of lists. Array representation of
lists was made possible through indices. The I-th element of the list was stored in the I-
th index of some array. This is also known as “sequential” representation of a list. In
“linked” representation, each of a list is stored in a node where a node contains two
pieces of information. The first part of information. The first part of the node is the data
item of the element of the list. The second part of the node is a “link reference can
definitely be the run-time address of the next node but it must be borne in mind that it is
not necessary for a reference to contain physical address of the memory where the next
node is stored. The basic point is, one must be able to access the node is stored. The
basic point is, one must be able to access the node representing the next element of the
ordered list from a given node by using a reference of a node representing and ordered
list. Representation of an ordered list of integers gives by L = (10, -5,0,99) using links
may be depicted as shown in figure 3.1.

www.gtuking.blogspot.com
Note that each node typically contains a “data” field and a “link” field. Arrows in
figure 3.1 show the “link” fields. The reference to the next node. Observe the “link” field of
the last node. Since this node does not have any node as its next node, the “link” field is
typically set to a default value, which indicates the end of the list. The list is identified by a
reference to the first node, which has been shown by arrow to the first node.
Another difference must be noted between array and linked representations of
ordered lists. In arrays, almost always the elements in the ordered list are stored in
contiguous memory locations. However there is no such need if ordered lists are
represented using links. It is possible that actual address of the second node is less
(numerically) than the actual address of the first node.
In “C” programming language pointers are an automatic choice for implementing
linked list dada structure. Clearly, pointers hold actual address during run-time and
therefore, they are natural choice for implementing reference. More importantly, it must
be said that “linked” representation alone not solves the problem of overflow or fixed size,
which occur in array representation. To overcome these problems, programming languages
must provide facilities for

Acquiring memory for storage during run-time.


Dividing the memory into two parts like “data” part and “link” part.
Freeing memory during execution of the program once the need for the acquired
memory is over.

In the “C” programming language, the first and the third task may be performed
using standard library calls such as “malloc” and “free”. The second task involves
declaring self-referential structure, which has been discussed in the next section. The
standard library call “malloc” is a function that needs an integer as its argument. If a call
is made as “malloc (80)” then a chunk of eighty bytes is acquired and a pointer to the
first byte of the acquired chunk is returned. It may be pointed out here that if “malloc”
can not acquired the amount of storage asked for (most probably because the system
runs out of memory) then, “malloc” returns a pointer the value of which is “NULL”. So
every call to “malloc” should be checked to determine the value of what has been
returned. This detail has been omitted in most of the function described in the chapter.
Since ”malloc” is the function to dynamically acquire memory from the system, it will no
usually fail if the
System has enough memory to be acquired. Thus, the problem of overflow occurs only if
there is real shortage in space in the computing system, which cannot be during
execution of program. The library
Call “free” is used to return the chunk of bytes (that is no longer needed for program
execution) to the system. Ideally, every chunk of space that is acquired using “malloc”
must be returned using “free” in a given program. A few more points about “malloc” and
“free” would not be out of place. When a program is executed, a process is created.
Every process is associated with a “stack” and a “heap”. The stack is used for the storage
of automatic variables. Whatever space is reserved through “malloc”, it is acquired from
the heap. And that space available or returned to the system by an explicit call to “free”.
It would be proper for reader to understand the basic principles of pointers and the
working of “malloc” and “free” to completely the topics in this chapter.

2000 Address of a node


20 Data of a node
3000 Address of next node

www.gtuking.blogspot.com
head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

Insertion into a linked list

1. Insertion as a first node

Before insertion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
newNode 8000 4000 40 5000
8000 100 5000 50
NULL

www.gtuking.blogspot.com
After Insertion

Head 1000
8000 10 2000
2000 20 3000
3000 30 4000
newNode 8000 4000 40 5000
8000 100 5000 50
1000 NULL

www.gtuking.blogspot.com
2. Insertion at a desired position

Before Insertion

Head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL
newNode 8000
8000 100

After Insertion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
8000 40 5000
5000 50
NULL
newNode 8000
8000 100
4000

www.gtuking.blogspot.com
Append a node in a linked list

Before Append

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

newNode 8000
8000 100
NULL

After Appending

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
8000

newNode 8000
8000 100
NULL

www.gtuking.blogspot.com
Deletion from a Linked List

Deletion of a first node

Before Deletion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

After Deletion

head 1000
2000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

Deletion of a desired node


Before deletion
head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

After deletion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

www.gtuking.blogspot.com
Program for Singly Linked List

/* Singly Linked List */

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

/* Structure Declaration */

struct LinkedList
{
int info;
struct LinkedList *next;
};

typedef struct LinkedList node;

/* Function Declaration */

void create(node *);


void print(node *);
void sort(node *);

int search(node *,int);


int count(node *);

node *insert(node *,int);


node *del(node *,int);
node *add(node *);

/* Main Function */

void main()
{
node *head = NULL;
node *temp;
int key;
int result;

int choice;

do
{

clrscr();
printf("\n1. Create");
printf("\n2. Print");
printf("\n3. Insert");
printf("\n4. Delete");
printf("\n5. Search");
printf("\n6. Sort");

www.gtuking.blogspot.com
printf("\n7. Add");
printf("\n8. Count");
printf("\n9. Exit");

printf("\n\nYour Selection is : ");


scanf("%d",&choice);

switch(choice)
{
case 1:
head = (node *)malloc(sizeof(node));
printf("Enter No : ");
scanf("%d",&head->info);
create(head);
break;
case 2:
print(head);
break;
case 3:
printf("\nEnter the key value : ");
scanf("%d",&key);

temp = insert(head,key);

if(temp == NULL)
printf("\nKey value not found...");
else
head = temp;
break;
case 4:
printf("\nEnter the key value : ");
scanf("%d",&key);

temp = del(head,key);
if(temp == NULL)
printf("\nKey value not found....");
else
head = temp;
break;
case 5:
printf("\nEnter the key value : ");
scanf("%d",&key);
result = search(head,key);

if(result == 1)
printf("\nSearch Successful...");
else
printf("\nSearch Unsucessful...");
break;
case 6:
sort(head);
break;
case 7:

www.gtuking.blogspot.com
head = add(head);
break;
case 8:
result = count(head);
printf("\nTotal nodes in the list : %d",result);
break;
case 9:
exit(0);
}

getch();

} while(choice != 9);
}

/* Create Function */

void create(node *tempHead)


{
char choice;

printf("\nDo you want to continue...");


fflush(stdin);
choice = getchar();

while(choice != 'n' && choice != 'N')


{
tempHead->next = (node *)malloc(sizeof(node));
tempHead = tempHead->next;

printf("Enter No : ");
scanf("%d",&tempHead->info);

printf("\nDo you want to continue...");


fflush(stdin);
choice = getchar();
}
tempHead->next = NULL;
}

/* Print Function */

void print(node *tempHead)


{
while(tempHead != NULL)
{
printf("%d\n",tempHead->info);
tempHead = tempHead->next;
}
}

/* Insert Function */

www.gtuking.blogspot.com
node *insert(node *tempHead,int key)
{
node *newNode,*temp = tempHead;
int result;

result = search(tempHead,key);

if(result == 0)
return NULL;

newNode = (node *)malloc(sizeof(node));


printf("Enter new value : ");
scanf("%d",&newNode->info);

if(tempHead->info == key)
{
newNode->next = tempHead;
tempHead = newNode;
return tempHead;
}
else
{
while(tempHead->next->info != key)
tempHead = tempHead->next;

newNode->next = tempHead->next;
tempHead->next = newNode;
return temp;
}
}

/* Delete Function */

node *del(node *tempHead,int key)


{
node *temp = tempHead;
node *tempNode;
int result;

result = search(tempHead,key);

if(result == 0)
return NULL;

if(tempHead->info == key)
{
tempNode = tempHead;
tempHead = tempHead->next;
free(tempNode);
return tempHead;
}
else
{

www.gtuking.blogspot.com
while(tempHead->next->info != key)
tempHead = tempHead->next;

tempNode = tempHead->next;
tempHead->next = tempHead->next->next;

free(tempNode);
return temp;
}
}

/* Search Function */

int search(node *tempHead,int key)


{
while(tempHead != NULL)
{
if(tempHead->info == key)
return 1;
tempHead = tempHead->next;
}

return 0;
}

/* Sort Function */

void sort(node *tempHead)


{
node *storeHead = tempHead;
int noOfNodes = count(tempHead);
int tempInfo;
int i,j;

for(i=noOfNodes-1;i>0;i--)
{
tempHead = storeHead;

for(j=0;j<i;j++)
{
if(tempHead->info > tempHead->next->info)
{
tempInfo = tempHead->info;
tempHead->info = tempHead->next->info;
tempHead->next->info = tempInfo;
}
tempHead = tempHead->next;
}
}
}

/* Add Function */

www.gtuking.blogspot.com
node* add(node *tempHead)
{
node *temp = tempHead;
node *newNode;
newNode = (node *)malloc(sizeof(node));
printf("\nEnter No : ");
scanf("%d",&newNode->info);
newNode->next = NULL;

if(tempHead == NULL)
return newNode;

while(tempHead->next != NULL)
tempHead = tempHead->next;

tempHead->next = newNode;
return temp;
}

/* Count Function */

int count(node *tempHead)


{
int result = 0;

while(tempHead != NULL)
{
result++;
tempHead = tempHead->next;
}
return result;
}

Doubly linked lists

Linked lists that have been considered so far contain only one link field, which
points to another node in the list. This is why these lists are also referred to as singly
connect linked lists. It has been pointed out that such lists, sometimes, are too restrictive.
For example it has been seen that in order to delete a node pointed to by “P”, another
pointer “q”, pointing to the preceding node is required to be known. One way to find out
“q” is to start from out “q” is to start from the beginning of the list and traverse the list to
the node whose “next” field is equal to “p”. This pointer “q” would not have been necessary
if another link field pointing to the previous node is maintained with every node in the list.
In that case every node will have two link fields: previous and next. Then, it would be easy
to move to either left or right from any given node.

If the links are implemented through pointers than two pointers are to be introduced
to each node of the list instead of one pointer. One of these pointers will point to the next
node to its right and the pointer will point to the preceding node to its left. The type
declaration for such a node containing integers is as follows.

typedef stuck intdnode

www.gtuking.blogspot.com
{
int data;
struct intdnode * right,* left;
} intdnode;

pictorially, each node may be depicted as Figure 3.12

Figure 3.12. A node in a doubly connected list.

4000 Address of a node


5000 Address of previous node
40 Data of a node
5000 Address of next node

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
NULL

Insertion into a doubly linked list

As a first node

Before Insertion

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
newNode 8000 3000 30 3000 5000
8000 4000 40 4000
100 5000 50
NULL

After Insertion

head 1000
8000 8000 2000
10 1000 3000
2000 20 2000 4000

www.gtuking.blogspot.com
newNode 8000 3000 30 3000 5000
8000 NULL 4000 40 4000
100 5000 50
1000 NULL

www.gtuking.blogspot.com
Append a node to doubly linked list

Before Append

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
NULL
8000
NewNode
8000 100
NULL

After Append

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
8000
8000
NewNode 5000
8000 100
NULL

www.gtuking.blogspot.com
Deletion of node

Deletion of a first node

Before deletion

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
NULL

After Deletion

head 1000
1000 NULL 2000
10 NULL 3000
20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
NULL

Deletion of a desired node

Before deletion

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
NULL

After deletion

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
5000 40 3000
5000 50
NULL

www.gtuking.blogspot.com
Insertion at a desired position

Before Insertion

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 3000 5000
4000 40 4000
5000 50
newNode 8000 NULL
8000
100

After Insertion

head 1000
1000 NULL 2000
10 1000 3000
2000 20 2000 4000
3000 30 8000 5000
8000 40 4000
5000 50
newNode 8000 NULL
8000 4000
100
3000

Program For Doubly Linked List

/* Doubly Linked List */

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

struct DLink
{
int info;
struct DLink *next;
struct DLink *prv;
};

typedef struct DLink node;


void create(node *);
void print(node *);
node *insert(node *);

www.gtuking.blogspot.com
node *del(node *);

/* Main Function */

void main()
{
node *head;
int choice;

clrscr();

do{

printf("\n1. Create");
printf("\n2. Print");
printf("\n3. Insert");
printf("\n4. Delete");
printf("\n5. Exit");

printf("\n\nYour Selection is : ");


scanf("%d",&choice);

switch(choice)
{
case 1:
head = (node *)malloc(sizeof(node));
head->prv = NULL;
printf("Enter No : ");
scanf("%d",&head->info);
create(head);
break;
case 2:
print(head);
break;
case 3:
head = insert(head);
break;
case 4:
head = del(head);
break;
}

} while(choice != 5);
}

/* Create Function */

void create(node *list)


{
while(list->info != -999)
{
list->next = (node *)malloc(sizeof(node));
list->next->prv = list;

www.gtuking.blogspot.com
list = list->next;
printf("Enter No : ");
scanf("%d",&list->info);
}
list->next = NULL;
}

/* Print Function */

void print(node *list)


{
while(list->next != NULL)
{
printf("%d\n",list->info);
list = list->next;
}
list = list -> prv;

while(list != NULL)
{
printf("%d\n",list->info);
list = list->prv;
}
}

/* Insert Function */

node *insert(node *list)


{
int key;
node *new1,*temp = list;
printf("Enter Key Value : ");
scanf("%d",&key);
new1 = (node *)malloc(sizeof(node));
printf("Enter new value : ");
scanf("%d",&new1->info);

if(list->info == key)
{
new1->next = list;
list->prv = new1;
new1->prv = NULL;
list = new1;
return list;
}
else
{
while(list->next->info != key)
{
if(list->next->next == NULL)
{
printf("\nKey Not Found....");
return temp;

www.gtuking.blogspot.com
}
list = list->next;
}
new1->next = list->next;
list->next->prv = new1;
new1->prv = list;
list->next = new1;
return temp;
}
}

/* Delete Function */

node *del(node *list)


{
int key;
node *temp = list;
node *tempNode;
printf("\nEnter key value : ");
scanf("%d",&key);

if(list->info == key)
{
tempNode = list;
list->next->prv = list->prv;
list = list->next;
free(tempNode);
return list;
}
else
{
while(list->next->info != key)
{
if(list->next->next == NULL)
{
printf("\nKey Not Found....");
return temp;
}
list = list->next;
}

tempNode = list->next;
list->next = list->next->next;
list = list->next;
list->prv =list->prv->prv;
free(tempNode);
return temp;
}

www.gtuking.blogspot.com
Circular Lists

In some application it may be more convenient if the linked field of the last node
in a singly connected linked list points back to the first node of the list, Such a list is called
a circular linked list as a shown in figure 3.17

Algorithm for traversing a circular list is slightly different than the same algorithm
for a singly connected linked list because “NULL” is not encountered as the link field for
any node in a circular list. For traversing a circular list, one needs to save the starting
pointer and traverse as long as the link field of a node becomes equal to the saved pointer.
Sometimes it is advantageous to identify a circular list by the pointer to the last node in
the list as shown in the figure 3.18

Particularly, insertion of a node at the start or end of a circular list identified by a


pointer to the last node of the list takes a constant amount of time irrespective of the
number of nodes in the list. Similar benefit is also enjoyed when two circular lists are
concatenated.

2000 Address of a node


20 Data of a node
3000 Address of next node

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
1000

Insertion into a linked list

www.gtuking.blogspot.com
3. Insertion as a first node

Before insertion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
newNode 8000 4000 40 5000
8000 100 5000 50
NULL

After Insertion

head 1000
8000 10 2000
2000 20 3000
3000 30 4000
newNode 8000 4000 40 5000
8000 100 5000 50
1000 8000

www.gtuking.blogspot.com
4. Insertion at a desired position

Before Insertion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
1000
newNode 8000
8000 100

After Insertion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
8000 40 5000
5000 50
1000
newNode 8000
8000 100
4000

www.gtuking.blogspot.com
Append a node in a linked list

Before Append

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
1000

newNode 8000
8000 100
NULL

After Appending

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
8000

newNode 8000
8000 100
1000

www.gtuking.blogspot.com
Deletion from a Linked List

Deletion of a first node

Before Deletion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
1000

After Deletion

head 1000
2000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
2000

Deletion of a desired node


Before deletion
head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
1000

After deletion

head 1000
1000 10 2000
2000 20 3000
3000 30 4000
4000 40 5000
5000 50
NULL

www.gtuking.blogspot.com
Program for Circular Singly Linked List

/* Singly Linked List */

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

/* Structure Declaration */

struct CirLinkedList
{
int info;
struct CirLinkedList *next;
};

typedef struct CirLinkedList node;

/* Function Declaration */

void create(node *);


void print(node *);
void sort(node *);

int search(node *,int);


int count(node *);

node *insert(node *,int);


node *del(node *,int);
node *add(node *);

/* Main Function */

void main()
{
node *head = NULL;
node *temp;
int key;
int result;

int choice;

do
{

clrscr();
printf("\n1. Create");
printf("\n2. Print");
printf("\n3. Insert");
printf("\n4. Delete");

www.gtuking.blogspot.com
printf("\n5. Search");
printf("\n6. Add");
printf("\n7. Count");
printf("\n8. Exit");

printf("\n\nYour Selection is : ");


scanf("%d",&choice);

switch(choice)
{
case 1:
head = (node *)malloc(sizeof(node));
printf("Enter No : ");
scanf("%d",&head->info);
create(head);
break;
case 2:
print(head);
break;
case 3:
printf("\nEnter the key value : ");
scanf("%d",&key);

temp = insert(head,key);

if(temp == NULL)
printf("\nKey value not found...");
else
head = temp;
break;
case 4:
printf("\nEnter the key value : ");
scanf("%d",&key);

temp = del(head,key);
if(temp == NULL)
printf("\nKey value not found....");
else
head = temp;
break;
case 5:
printf("\nEnter the key value : ");
scanf("%d",&key);
result = search(head,key);

if(result == 1)
printf("\nSearch Successful...");
else
printf("\nSearch Unsucessful...");
break;
case 6:
head = add(head);
break;

www.gtuking.blogspot.com
case 7:
result = count(head);
printf("\nTotal nodes in the list : %d",result);
break;
case 8:
exit(0);
}

getch();

} while(choice != 8);
}

/* Create Function */

void create(node *tempHead)


{
char choice;
node *storeHead = tempHead;

printf("\nDo you want to continue...");


fflush(stdin);
choice = getchar();

while(choice != 'n' && choice != 'N')


{
tempHead->next = (node *)malloc(sizeof(node));
tempHead = tempHead->next;

printf("Enter No : ");
scanf("%d",&tempHead->info);

printf("\nDo you want to continue...");


fflush(stdin);
choice = getchar();
}
tempHead->next = storeHead;
}

/* Print Function */

void print(node *tempHead)


{
node *storeHead = tempHead;

do
{
printf("%d\n",tempHead->info);
tempHead = tempHead->next;
}while(tempHead != storeHead);
}

/* Insert Function */

www.gtuking.blogspot.com
node *insert(node *tempHead,int key)
{
node *newNode,*storeHead = tempHead;
int result;

result = search(tempHead,key);

if(result == 0)
return NULL;

newNode = (node *)malloc(sizeof(node));


printf("Enter new value : ");
scanf("%d",&newNode->info);

if(tempHead->info == key)
{
while(tempHead->next != storeHead)
{
tempHead = tempHead->next;
}

tempHead->next = newNode;

newNode->next = storeHead;
storeHead = newNode;
return storeHead;
}
else
{
while(tempHead->next->info != key)
tempHead = tempHead->next;

newNode->next = tempHead->next;
tempHead->next = newNode;
return storeHead;
}
}

/* Delete Function */

node *del(node *tempHead,int key)


{
node *storeHead = tempHead;
node *tempNode;
int result;

result = search(tempHead,key);

if(result == 0)
return NULL;

if(tempHead->info == key)

www.gtuking.blogspot.com
{

if(tempHead->next == tempHead)
return NULL;
tempNode = tempHead;

while(tempHead->next != storeHead)
tempHead = tempHead->next;

tempHead->next = storeHead->next;
storeHead = storeHead->next;

free(tempNode);
return storeHead;
}
else
{
while(tempHead->next->info != key)
tempHead = tempHead->next;

tempNode = tempHead->next;
tempHead->next = tempHead->next->next;

free(tempNode);
return storeHead;
}
}

/* Search Function */

int search(node *tempHead,int key)


{
node *storeHead = tempHead;

do
{
if(tempHead->info == key)
return 1;
tempHead = tempHead->next;
}while(tempHead != storeHead);

return 0;
}

/* Add Function */

node* add(node *tempHead)


{
node *storeHead = tempHead;
node *newNode;

newNode = (node *)malloc(sizeof(node));


printf("\nEnter No : ");

www.gtuking.blogspot.com
scanf("%d",&newNode->info);

newNode->next = storeHead;

if(tempHead == NULL)
return newNode;

while(tempHead->next != storeHead)
tempHead = tempHead->next;

tempHead->next = newNode;
return storeHead;
}

/* Count Function */

int count(node *tempHead)


{
node *storeHead = tempHead;
int result = 0;

if(storeHead == NULL)
return 0;
do
{
result++;
tempHead = tempHead->next;

}while(tempHead != storeHead);

return result;
}

Stacks and Queues

Stacks and queues are special kinds of linear lists. It may be recalled that a linear
list is an ordered collection of a number of items of the same type. A linear list ,L, of “n”
elements is usually denoted by L=(a1,a2,….,an) where “a1” represents the I-th element of
the list. Two operation that are frequently performed on a linear list, these are insertion
into and deletion from a list. In the case of an ordinary linear list, these two operations
may be performed at nay position in the list. Thus, insertion before the fifth element or
deletion of the tenth element of a list is perfectly valid operations as long as the list
contains the required number of elements. A stack is a linear list where all insertions and
deletions are permitted only at one end of the list. Thus, if elements are continuously
inserted into a stack then, it grows at one end. And if an element is deleted from a stack
then it shrinks at the same end. Figure 4.1 depicts this expansion and shrinking of a stack.
Initially the stack is empty. As the elements A,B,C,D,E are inserted into it, the stack grows
continually upward. And if two elements are deleted from the stack, it is clear that the
element that is removed from stack. From the very nature of a stack, it is clear that the
element that is removed from a stack has been the last element inserted into the stack.

www.gtuking.blogspot.com
For example, the first element deleted from the stack in Figure 4.1 was E, which had been
the last element to be inserted into the stack. This is why a stack is often called a “Last In
First Out(LIFO)” list.

Array representation of stack with five elements for following operations

1. insert 10
2. insert 20
3. insert 30
4. delete node
5. delete node
6. insert 40
7. insert 50

10 push(10)

www.gtuking.blogspot.com
push(20)
10 20

10 20 30
push(30)

pop( )
10 20

pop( )
10

push(40)
10 40

push(50)
10 40 50

Program for Stack Using array

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

#define SIZE 5

int stack[SIZE];
int tos = -1;

void main()
{
int choice;

do
{
clrscr();
printf("1. Push\n2. Pop\n3. Peep\n4. Print\n5. Exit");
printf("\nEnter Your Choice.... : ");
scanf("%d",&choice);

switch(choice)
{
case 1:
push();

www.gtuking.blogspot.com
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
print();
break;
case 5:
exit(0);
}
getch();
}while(choice != 5);
}

push()
{
int val;
if(tos == SIZE - 1)
{
printf("\nstack Overflow...");
}
else
{
printf("\nEnter Value : ");
scanf("%d",&val);
tos = tos + 1;
stack[tos] = val;
}
}

pop()
{
if(tos == -1)
{
printf("\nstack Underflow...");
}
else
{
printf("\nDeleted element is : %d",stack[tos]);
tos = tos - 1;
}
}
peep()
{
int no;
printf("\nEnter the element no : ");
scanf("%d",&no);
if(no<=tos+1)
printf("\nYour element is : %d",stack[no-1]);

www.gtuking.blogspot.com
else
printf("\nNo of elements in a stack is %d",tos+1);
}
print()
{
int i;

if(tos == -1)
printf("\nStack is Empty...");
else
for(i=tos;i>=0;i--)
printf("\n%d",stack[i]);
}

Linked list representation of stack for following operations

1. insert 10
2. insert 20
3. insert 30
4. delete node
5. delete node
6. insert 40
7. insert 50

Address
2000 of a
node
20 1000

Data Address of next node

head
NULL

head 1000
1000 10 NULL push(10)

head 2000 1000


push(20)
2000 20 1000 10 NULL

www.gtuking.blogspot.com
head 3000 2000 1000
push(30)
3000 30 2000 20 1000 10 NULL

head 2000 1000


pop( )
2000 20 1000 10 NULL

head 1000
1000 10 NULL pop( )

head 4000 1000


push(40)
4000 40 1000 10 NULL

head 5000 4000 1000


push(50)
5000 50 4000 40 1000 10 NULL

Program for Stack Using Linked List

/* Creation of a stack uning linked list */

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

struct stack
{
int info;
struct stack *next;
};

typedef struct stack node;


node *head = NULL;

void push();
void pop();
void peep();

www.gtuking.blogspot.com
void print();

void main()
{
int choice;

do
{
clrscr();
printf("1. Push\n2. Pop\n3. Peep\n4. Print\n5. Exit");
printf("\nEnter Your Choice.... : ");
scanf("%d",&choice);

switch(choice)
{
case 1:
push();
break;
case 2:
pop();
getch();
break;
case 3:
peep();
getch();
break;
case 4:
print();
getch();
break;
case 5:
exit(0);
}
}while(choice != 5);
}

void push()
{
int val;
node *newNode;
printf("\nEnter value : ");
scanf("%d",&val);
newNode = (node *)malloc(sizeof(node));
newNode->info = val;

newNode->next = head;
head = newNode;
}

void pop()
{
node *temp;
if(head == NULL)

www.gtuking.blogspot.com
{
printf("Stack Underflow....");
return;
}
else
{
printf("Value popped : %d",head->info);
temp = head;
head = head->next;
free(temp);
}

void peep()
{
int no,i=0;
node *temp = head;
printf("\nWhich node you want to view : ");
scanf("%d",&no);

while(temp != NULL)
{
if(i == no-1)
{
printf("Peeped element is : %d",temp->info);
return;
}
temp = temp->next;
i++;
}
printf("Can't find element no %d...",no);

void print()
{
node *temp = head;

if(temp == NULL)
{
printf("\nStack is empty...");
return;
}

while(temp != NULL)
{
printf("\nNo : %d",temp->info);
temp = temp->next;
}
}

www.gtuking.blogspot.com
A queue, like a stack, is another special type of ordered list. A queue is an ordered
list where insertions are permitted at one end of the list and deletion is permitted at the
other end of the list. By convention, the end where insertions are performed is called the
“rear” of the list and the other end from where deletions are done is called the “front” of
the list. The names of the ends are so chosen that the queue data structure resembles the
queues in every day life. In Figure 4.2, addition to a queue is explained. The queue is
initially empty. Elements „A‟,‟B‟,‟C‟,‟D‟ are added to queue one by one and the queue grows
to the right. Naturally, the “rear” end of the queue also shifts towards right but the “front”
end remains at the current first element „A‟. If an element is removed from the queue, the
element at the front (i.e., ‟A‟) will be removed and “front” end shifts to the next element in
the queue. See that the first element removed is the first element added to the queue.
Hence, a queue is often called First In First Out(FIFO) list

Stacks and queues can also be defined as Abstract data Type (ADTs). A stack of
element of data of type T is a finite sequence of element of T together with the following
operation

A. Initialize a stack as an empty stack.


B. Determine if a stack is Empty or not.
C. Determine if a stack is Full of not .
D. If a stack is not a full ,then push a new node at one end of the stack ,called its top .
E. If a stack is not empty ,then retrieve the node at its top.
F. a stack is not empty, then pop the node at its top.
G. Copy one stack to another stack.

A queue of element of type T is finite sequence of element of together With the following

www.gtuking.blogspot.com
A. Initialize a queue to be empty.
B. Determine if a queue is empty or not.
C. Determine if a queue is full or not
D. If Add a new node after the last node in a queue (i.e., at the “read” end of the
queue ) if it is not full.
E. Retrieve the first node of a queue, if it is not empty.
F. Remove the first node in a queue (i.e., at the “front” end of the queue ), if it is not
empty

Trees

“Trees” is one of the most important nonlinear data structure in computer


algorithms .A tree structure depicts a hierarchical relationship among the nodes of the
tree . “parent-child”, relationship is a typical hierarchical relationship. Consider
representing parent-child relationship among persons in a family. A hypothetical family
tree is show in figure 7.1

In figure 7.1 each node represent a person whose name is written against that node
as its label. Each line connecting two nodes in the figure denotes a relationship namely
“parents-child” relation between the connected nodes. if a node “X” is connected to a node
“Y” and “X” is above “Y” in the tree then “X” is a parent of “Y” and “Y” is a child of “X”. For
instance, the node labeled “prakash” is a parent of nodes labeled “Anita” ,”Raju” and
“soumen” .similarly, the nodes labeled by “partha” and children of the node labeled by its
label and this convention will be used in the remaining part if this book. It is to be noted
that the tree originated from a unique node. For example, “prakash” is the label of the top
–most nodes in the family tree as show in figure 7.1 such a nodes, which does not have

www.gtuking.blogspot.com
any parent, is called the “root” node. Also note that the tree can be horizontally divided
into several .nodes in the same level may also enjoy a relationship . in this case,
The relationship is the “sibling” relationship. For instance, Anita is a sister of Raju
and soumen. Raju soumen are brother of Anita. These may even exist a relationship
among nodes, which are not directly connected . In figure 7.1 Mala is a granddaughter of
Prakash and Prakash is the grandfather of Mala. So, it should not be assumed that there is
no relationship between nodes, which are not connected.
Consider anther simple example, which further illustrates the idea of representing
hierarchical relationships by means of trees. Consider simple “reporting to” relationship
among employees in an organization. A simplified version of the employee hierarchy in a
typical software organization is shown in Figure 7.2.
In Figure 7.2, each node represents a designated person. A line connecting two
nodes represents a reporting relationship. From Figure 7.2, it is seen that the node

„CEO‟ is above the node „SVP‟ (Senior Vice-President) and these two nodes are connected.
This implies that a senior vice-president reports to the CEO. Similarly, a PL(Project Leader)
reports to a PM(Project Manager). It should be noted that there is no reporting relationship
between nodes in the same level. This tree originates from a unique node. „CEO‟ which is
the root node of this tree.

Definition of trees

www.gtuking.blogspot.com
A tree may be defined as a finite set “T” of one or more nodes such that: (a) there
is a specially designated node called the root of the tree, (b) the remaining nodes
(excluding the root) are partitioned into n>=0 disjoint sets T1,T2,…,Tn and each of these
sets is a tree in turn. The trees T1,T2,…,Tn are called the sub-trees (or children) of the
root. Note that the definition is recursive as the children of the root of a tree are trees once
again.

In Figure 7.1, the root of the family tree is “Prakash”. It has three sub-trees or
children, rooted at “Anita”, “Raju” and “Soumen”. As the sub-trees are disjoint sets by
definition, the sub-trees rooted at “Anita”, “Raju” and “Soumen” in Figure 7.1 are
independent and the nodes in these trees are not anyway connected to one another. It can
also be said that every node in a tree is the root f some sub-tree.

Therefore, Soumen is the root of a sub-tree of Prakash, which has two sub-trees
Partha and Mou. A node may also have an empty sub-tree as one of its child. For example,
Goutam is a root of a tree with no sub-trees, which do not have any children, are called
leaf or terminal nodes.

If a line is drawn from the node “Goutam” to the node “Raju” then both the nodes
“Raju” and “Anita” become the parents of “Goutam”. That is, more than one node becomes
the parent of another node. Moreover, a cycle is formed containing four nodes – Prakash,
Anita, Goutam and Raju. This scenario is depicted in Figure 7.3.

Obviously, both the sub-trees rooted at “Anita” and “Raju” contain the same node
“Goutam “ and therefore, these sub-trees are not disjoint. According to the definition of a
tree ,these sub trees must be disjoint. So, the diagram in Figure 7.3 does not represent a
tree.

Generally, it is a convention to draw the root node at the top and to let the tree
grow downwards. This convention is followed while drawing trees in Figure 7.1 and 7.2 .
However , this is merely a convention and it is not mandatory to follow this convention.

Number of nodes connected by links to a given node “n” is called the degree of the
node “n”. For example ,degree of the node “SVP” in Figure 7.2 is 3 and degree of the node

www.gtuking.blogspot.com
“SE” is 1. Degree of a leaf node or a terminal node is always 1. Some examples of general
trees are shown in Figure 7.4.

The level of a node is recursively defined as follows. The level of the root node is
defined as 0. The level
Any other node is one more than the level of parent . In Figure 7.4(b),the level of node
“D” is 2(i.e., one higher then the level of its parent “B” which is 1).

If a node “y” is a child of another node “x” is said to be the parent of “y”. For
example , the node “E” in the tree of Figure 7.4(b) is the node “C”. The links between a
parent and its children are also referred to as edges or branches. An edge may be defined
as a tuple (x,y), which denotes the link between the node to another, is often termed as a
path. For example, the collection of edges {(V,S),(S,P),(P,R),(R,U)} denotes a path from
the node “V” to the node “U” in the tree of Figure 7.4(c). All nodes occurring in the path
from a given node “n” to the root of a tree are called ancestors of “n”.

Binary tree

Binary tree is an important class of tree data structure in which a node can have at
most two children (which are sub-tree). Moreover, children (or the sub-tree) of a node of
a binary tree are ordered. One child is called the “left” child and the other is called the
“right” child .an example of a binary tree is show in figure 7.5

www.gtuking.blogspot.com
In figure 7.5 the node “a” (which is the root node) has two children “b” and “c”
similarly, each of the nodes “B”, “D” and “E” has only one child “D”, “H” and “G”
Respectively. As every node in tree is the root of some other sub-tree ,”b” and “c
” are the root of the sub-tree of the node “A”. in figure 7.5 the node “E” has a left sub-tree
rooted of the at “G” and the node “B” has a right sub-tree rooted at “D” only. The nodes
“H”, “G” and the node sub-tree and leaf nodes in this tree
Similarly to a tree . a binary tree may also be defined recursively as follows .
1) an empty tree is binary tree.
2) A binary tree consist of a node called “root”, a left sub-tree and right sub-tree
both of which are binary tree once again
3)
If should be clear that, by definition, any non-empty binary tree is a tree as well.
Example of some binary tree is show in figure 7.6.
Note that, binary tree drawn in figure 7.6(ii) and 7.6(iii) are distinct since the root of the
binary tree of figure 7.6(ii) has an empty right sub-tree while the root of the binary tree
of figure 7.6(iii) has an empty left sub-tree. But, the tree of figure 7.6(ii)&(iii) are
identical, as the ordering of the sub-tree of figure 7.6 (ii)&(iii) are identical, as the
ordering of the sub-tree of the root is not significant for trees Thus, it must be noted that
are fundamental difference between a binary tree and tree.

www.gtuking.blogspot.com
Level of a node in a binary tree is defined in the same way as level is defined for
nodes of a general tree. For example, the level of the node “D” of the tree of Figure
7.6(iv), is one higher than the level of node “C” (which is the parent of node “D”). The
root node “A” has a level 0. Therefore, the level of “C” is 1 and level of “D” is 2.

Height of a binary tree

The height of a binary tree “T”, denoted by height (T), is defined as follows
Height(T) = maximum level of any node of a binary tree “T”.
Consider the binary tree of Figure 7.6(iv). The maximum level of any node in this free
Therefore, height of this tree is 4.
If all non-leaf nodes of a binary tree have exactly two non-empty children and the levels of
all leaf nodes of a binary tree are the same then the tree is called a complete or a full
binary tree.

www.gtuking.blogspot.com
Tree as the levels of the leaf nodes “B” and “D” are not the same and there is a
node “C” which has only one non-empty child. An example of a full binary tree is shown in
figure 7.7,

Representation of a Binary Tree using pointer

A non-empty binary tree consists of a root and two children , which are binary
trees once again. Since the definition of this data structure is recursive, an appropriate
representation could be self-referential structures. Each node of the tree is represented by
a structure. Each node contains two links to the same structure – “left” and “right” as
shown in Figure 7.8 (b). The linked list representation of the tree of Figure 7.8 (a) is
shown in Figure 7.8 (c). A straightforward implementation of this representation can be
done by using pointers to implement the links. Let “T” be the link to the root node of a
tree. If “T” is null, then the tree is empty; otherwise “T” points to the root node of the tree,
“left” link points to the left sub-tree of “T” and the right link points to the right sub-tree of
“T”.

www.gtuking.blogspot.com
Binary tree traversal

Traversal of a binary tree is one of the most important operations required to be


done on a binary tree. Many other operations involving binary tree data structure often
need to traverse or walk through a given tree. Traversing is a process of visiting every
node in the tree exactly once. Therefore, a complete traversal of a binary tree implies
visiting the nodes of a tree in some linear sequence. Since a in a binary tree is defined in a
recursive manner, its traversal can necessarily be defined in an identical recursive fashion.
For example, to traverse a binary tree, one may first visit the root, then traverse the left
sub-tree and finally traverse the right sub-tree. Traversing a binary tree in this manner will
produce a particular sequence of visits to the nodes. One may traverse the tree in a
different manner (e.g., first traverse the left sub-tree then visit the root and finally
traverse the right sub-tree) and a different sequence of visits to the nodes will be
produced. It is easy to verify that six such different combinations are possible. If it is
conventionally assumed that visiting the left sub-tree always precedes visiting the right
sub-tree then only three different combination remain which know as Inorder, preorder
and postorder tree traversal. In the following, these three kinds of traversal techniques
are explained along with the necessary algorithms.

Inorder Traversal

If a tree “T”, is traversed in an “Inorder” fashion then the left sub-tree of “T” is
traversed first, then the root node of “T” is visited and then the right sub-tree of “T” is
traversed. Quite understandably , the left (as well as the right) sub-tree of “T” Could be
another binary tree and these fore, traversing is to be done on “T” in case “T” is empty,
then traversal of “T” involve doing noting. The “C” function for

www.gtuking.blogspot.com
Inorder traversal of a tree is as follows. It is assumed that the type of each node in the
tree is “as described earlier. Each node contains a character as its information and it is
also assumed that visiting each node involves printing the information associated with
that node.

Void Inorder (bNode *T)


{
if (T!=NULL)
{
Inorder (T->left);
printf(“%c”,T->data);
Inorder (T->right);
}
return;
}

If this function is executed on the tree of figure 7.8(a) then the following output
would be produced.

D G B H E A F I C

Preorder Traversal

If a tree, “T”, is traversed in “preorder” fashion then the root node of “T” is visited
first and then the left sub-tree of “T” is traversed and finally the sub-tree of “T” is
traversed. As before, if T is NULL then traversed of “T” involves doing nothing. Translating
these ideas, the following “C” function for preorder traversal is obtained.

void preorder(bNode *T)


{
if(T!=NULL)
{
printf(“%c”,T->data);
preorder(T->left);
preorder(T->right);
}
return;
}

If the binary tree of Figure 7.8(a) is traversed in preorder manner, then the
following output would be generated.

A B D G E H C F I

www.gtuking.blogspot.com
Postorder Traversal

If a tree “T” is traversed in “postorder” manner, then the left sub tree of “t” is
traversed first, then the right sub-tree of “T” is traversed and finally the root node of “T” is
visited. For an empty tree, T, is presented below.

void postorder(bNode *T)


{
if(T!=NULL)
{
Postorder(T->left);
Postorder(T->right);
printf( “%c”,T->data);
}
return;
}

The Postorder traversal of the binary tree of Figure 7.8(a) produces the following
output.

G D H E B I F C A

Binary search Tree

Binary search trees from an important sub-class of binary trees. In an ordinary


tree, the elements are not ordered in any way. However, data are ordered in many
applications. Information in the nodes in a binary search tree is maintained in some order.
Usually, the nodes in a binary search tree represent some records and these records are
ordered. Records are ordered on so0me key properties. Therefore, the information part of
a node in a binary search tree is assumed to have some key attributes. For the purpose of
studying binary search trees one may just concentrate on these keys. Thus, the
information field of nodes in a binary tree will be referred to as just keys.

A binary search tree is a binary tree which is either empty or in which the following
criteria are satisfied.

1. All keys of the left sub-tree of the root are “less than” the key in the root.
2. All keys of the right sub-tree of the root are “greater than” the key in the root.
3. The left and right sub-tree of a binary search tree are binary search trees once again.
The definition is recursive.

www.gtuking.blogspot.com
Program for Binary search Tree

/* Binary Search Tree */

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

struct tree
{
int info;
struct tree *left;
struct tree *right;
};

typedef struct tree node;

node *searchNode(node *,int);


node *deleteNode(node *,node *,node *);
node *deleteNodePredecessor(node *,node *,node *);
void print(node *,int);
int depthOfTree(node *, int);

node *root = NULL;


node *newNode = NULL;
node *parent=NULL;

int depth = 0;

void main()
{
int key;
int choice;
node *n;

clrscr();

do
{
clrscr();
printf("\n1. Create\n2. PreOrder\n3. PostOrder\n4. InOrder\n5. Search\n6. Insert
Delete(Predessesor)\n8. Delete(Successor)\n9. Print\n10. Depth\n11. Exit");
printf("\nYour choice is : ");
scanf("%d",&choice);

switch(choice)
{
case 1:
root=NULL;
create();
break;
case 2:

www.gtuking.blogspot.com
printf("\nPreOrder\n");
preorder(root);
getch();
break;
case 3:
printf("\nPostOrder\n");
postorder(root);
getch();
break;
case 4:
printf("\nInOrder\n");
inorder(root);
getch();
break;
case 5:
printf("\nEnter key : ");
scanf("%d",&key);

if(search(root,key))
{
printf("\nSuccessful.....");
}
else
{
printf("\nUnSuccessful....");
}
getch();
break;
case 6:
newNode = (node *)malloc(sizeof(node));
printf("Enter No : ");
scanf("%d",&newNode->info);
newNode->left = newNode->right = NULL;
insert(root,newNode->info);
break;
case 7:

printf("\nEnter key : ");


scanf("%d",&key);
n = searchNode(root,key);
if(n == NULL)
{
printf("\nKey Not Found...");
}
else
{
if(key == root->info)
parent = NULL;
root = deleteNodePredecessor(root,n,parent);
}
getch();
break;
case 8:

www.gtuking.blogspot.com
printf("\nEnter key : ");
scanf("%d",&key);
n = searchNode(root,key);
if(n == NULL)
{
printf("\nKey Not Found...");
}
else
{
if(key == root->info)
parent = NULL;
root = deleteNode(root,n,parent);
}
getch();
break;

case 9:
print(root,0);
getch();
break;
case 10:

depth = 0;
depth = depthOfTree(root,0);
printf("\nDepth of a tree is : %d",depth);
getch();
break;
case 11:
exit(0);
}

}while(choice != 11);
}

/* This function creates a Binary Search Tree */

create()
{
do
{
newNode = (node *)malloc(sizeof(node));
printf("Enter No : ");
scanf("%d",&newNode->info);
newNode->left = newNode->right = NULL;
if(newNode->info == 0)
break;

if(root == NULL)
{
root = newNode;
}
else

www.gtuking.blogspot.com
{
insert(root,newNode->info);
}
}while(newNode->info != 0);

return;
}

/* This function inserts a newInfo into an existing tree */

insert(node *tempRoot,int newInfo)


{
if(tempRoot->info > newInfo)
{
if(tempRoot->left == NULL)
{
tempRoot->left = newNode;
return;
}
else
{
insert(tempRoot->left,newInfo);
}
}
else
{
if(tempRoot->right == NULL)
{
tempRoot->right = newNode;
return;
}
else
{
insert(tempRoot->right,newInfo);
}
}
}

/* This function traverse the tree in preorder fashion */

preorder(node *tempRoot)
{
if(tempRoot)
{
printf("%d\n",tempRoot->info);
preorder(tempRoot->left);
preorder(tempRoot->right);
}
}
/* This function traverse the tree in postorder fashion */
postorder(node *tempRoot)
{
if(tempRoot)

www.gtuking.blogspot.com
{
postorder(tempRoot->left);
postorder(tempRoot->right);
printf("%d\n",tempRoot->info);
}
}

/* This function traverse the tree in inorder fashion */

inorder(node *tempRoot)
{
if(tempRoot)
{
inorder(tempRoot->left);
printf("%d\n",tempRoot->info);
inorder(tempRoot->right);
}
}
/* This function search a key from a tree
if key is found then it will return 1 else 0 */

search(node *tempRoot,int key)


{
if(tempRoot == NULL)
return 0;
if(tempRoot->info == key)
return 1;

if(key<tempRoot->info)
return search(tempRoot->left,key);
else
return search(tempRoot->right,key);
}

/* This function finds a parent node of a key and returns a pointer to the keynode */

node * searchNode(node *tempRoot,int key)


{
if(tempRoot == NULL)
return NULL;
if(tempRoot->info == key)
return tempRoot;

if(key<tempRoot->info)
{
parent = tempRoot;
return searchNode(tempRoot->left,key);
}
else
{
parent = tempRoot;
return searchNode(tempRoot->right,key);
}

www.gtuking.blogspot.com
}

/* this function removes a node from a tree */

node *deleteNode(node *tempRoot,node *n,node *parentNode)


{
node *inordersuc,*x;

if((n->left != NULL) && (n->right != NULL))


{
parentNode = n;
inordersuc = n->right;

while(inordersuc->left != NULL)
{
parentNode = inordersuc;
inordersuc = inordersuc->left;
}

n->info = inordersuc->info;
n = inordersuc;
}

if(n->left == NULL)
{
if(parentNode != NULL)
{
if(parentNode->left == n)
parentNode->left = n->right;
else
parentNode->right=n->right;
x = tempRoot;
}
else
{
x = n->right;
}
return x;
}

if(n->right == NULL)
{
if(parentNode)
{
if(parentNode->left == n)
parentNode->left = n->left;
else
parentNode->right = n->left;
x = tempRoot;
}
else
{
x = n->left;

www.gtuking.blogspot.com
}
return x;

/***************/

node *deleteNodePredecessor(node *tempRoot,node *n,node *parentNode)


{
node *inorderpre,*x;

if((n->left != NULL) && (n->right != NULL))


{
parentNode = n;
inorderpre = n->left;

while(inorderpre->right != NULL)
{
parentNode = inorderpre;
inorderpre = inorderpre->right;

n->info = inorderpre->info;
n = inorderpre;
}

if(n->left == NULL)
{
if(parentNode)
{
if(parentNode->left == n)
parentNode->left = n->right;
else
parentNode->right=n->right;
x = tempRoot;
}
else
{
x = n->right;
}
return x;
}

if(n->right == NULL)
{
if(parentNode)
{
if(parentNode->left == n)
parentNode->left = n->left;

www.gtuking.blogspot.com
else
parentNode->right = n->left;
x = tempRoot;
}
else
{
x = n->left;
}
return x;
}
}

/***************/

int depthOfTree(node *tempRoot, int level)


{
if(tempRoot != NULL)
{
if(level > depth)
depth = level;
depthOfTree(tempRoot->left,level+1);
depthOfTree(tempRoot->right,level+1);
}
return depth;
}

void print(node *tempRoot,int level)


{
int i;
if(tempRoot)
{
print(tempRoot->right,level+1);
printf("\n");
for(i=0;i<level;i++)
printf(" ");
printf("%d",tempRoot->info);
print(tempRoot->left,level+1);
}
}

www.gtuking.blogspot.com

You might also like