Вы находитесь на странице: 1из 44

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

DATA STRUCTURES
1. Introduction
Data structure is an organized collection of related information. A data structure uses
logical and mathematical techniques to store and retrieve data in an efficient manner.
1.1 Types of Data Structures
Generally data structures are classified into two classes:

Linear Data structures


Non-linear data structures

1.1.1 Linear Data structures

Linear data structures, in which elements are organized in sequence or in one order. The
following are various linear data structures:

Arrays
Linked lists
Stacks
Queues

1.1.1.1 Arrays

An array is a collection of ordered elements of same type. (OR) Array is a collection of


subscripted variables of the same type.
The array with one subscript is called one-dimensional array and the array with two or
more subscripts are called multi-dimensional arrays.
Array is finite because it contains only limited number of elements.
1.1.1.2 Linked lists

A linked list is an ordered collection of nodes. Node is a data structures, which contains
two parts called data and link.
DATA LINK
DATA part is used to store element information and LINK part is used to store address of
the next node.
The following is a linked list with five elements:

First node pointing to second node, second node pointing to third node and so on, last
node pointing to NULL, which indicates end of linked list.
Generally, there are two types linked lists: single linked list and double linked list.
1.1.1.3 Stacks

A Stack is a linear data structure, in which elements are inserted and deleted at one end
called TOP. TOP is a pointer always pointing to top of the stack.
STCS-TVM : 9496366351

Page 1

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Stack is also called LIFO (Last-In First-Out) list, because last inserted element removed
first.

1.1.1.4 Queues

A Queue is a linear data structure, in which elements are inserted at one end called REAR
and deleted at one end called FRONT.
Queue is also called FIFO (First-In First-Out) list, because first inserted element removed
first.

1.1.2 Non-linear Data structures

A Non linear data structure is a data structure, in which elements are organized but not
ordered in one particular way. The following are the non-linear data structures:
Trees
Graphs
1.1.2.1 Trees

A tree is a non-linear data structure, in which elements are organized in hierarchical


manner.

A tree is a collection of one or more nodes organized in hierarchical manner with the
following properties:
a) One Special node called Root
b) Remaining nodes are divided into one or more sub-trees

STCS-TVM : 9496366351

Page 2

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Here A is the Root node. The remaining nodes are divided into two sub-trees T1 and T2.
1.1.2.2 Graphs

A graph is a set of vertices and edges. Here vertex is a node and edge connects two
vertices.
Formally , a graph G = ( V, E )
V = Set of vertices

and

E = Set of edges

For example ,consider the following un-directed graph:

Here V={ A,B,C,D,E,F} and E={ (A,B),(A,C),(B,D),(B,E),(C,D),(C,E),(D,F),(E,F) }


In the graph (A,B) is equal to (B,A)
For example ,consider the following directed graph:

Here V={ A,B,C,D,E,F} and E={ (A,B),(A,C),(B,D),(B,E),(C,E),(D,C),(E,F),(F,D) }


In the graph (A,B) is not equal to (B,A)

2. Linked lists
A linked list is an ordered collection of nodes. Node is a data structures, which contains
two parts called data and link.
DATA LINK

STCS-TVM : 9496366351

Page 3

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

DATA part is used to store element information and LINK part is used to store address of
the next node.
Generally, there are two types linked lists:

Single linked lists


Double linked lists

2.1 Single linked lists


A single linked list is a linked list, in which each node contains one data part and one link
part. The following figure shows single linked list:

Here HEADER is the first node in the linked list and last node is pointing to NULL.
Without HEADER it is not possible to identify the beginning of the linked list and the
same way without NULL it is not possible to identify the end of the linked list
The following are the single linked list operations:

Insertion
Deletion
Traversal

2.1.1 Insertion

Inserting a new element into the single linked list. The following are the three ways of
inserting a new element into the single linked list:

Insertion at begin
Insertion at end
Insertion at middle

2.1.1.1 Insertion at begin

Inserting a new node at the first position of the single linked list, i.e. the new node
becomes the first node in the linked list. The following figures illustrate this insertion:
A new node with element X before Insertion,

A new node with element X after Insertion,


First step,

STCS-TVM : 9496366351

Page 4

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Second step,

Now NEW node becomes HEADER node.


The following is the code for the insertion at begin operation:
new = malloc(sizeof(node));
new-> data = X;

New node creation and storing element

new->link = NULL;
new->link = header;

/* First step */

header = new;

/* Second step */

printf(\n Insertion at begin position successfully completed);


2.1.1.2 Insertion at end

Inserting a new node at the end position of the single linked list, i.e. the new node
becomes the last node in the linked list. The following figures illustrate this insertion:
A new node with element X before Insertion,

A new node with element X after Insertion,


First step, identify the last node in the linked list and give the name to the last node called
PTR.

Second step, PTR pointing to NEW node

Now NEW node become the last node in the linked list.
The following is the code for the insertion at end operation:

STCS-TVM : 9496366351

Page 5

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

new = malloc(sizeof(node));
new-> data = X;

New node creation and storing element

new->link = NULL;
ptr = header; /* Pointing to the first node in the linked list */
while ( ptr->link != NULL)
{
ptr = ptr->link;

Finding the last node in the


linked list

}
ptr ->link = new; /* new node inserted at the end of the linked list */
printf(\n Insertion at end position successfully completed);
2.1.1.2 Insertion at middle

Inserting a new node at the middle position of the single linked list. The following figures
illustrate this insertion:
A new node with element X before Insertion,

A key node with some element is used to identify the middle position of the linked list .
So that NEW node inserted after the identified key node.
A new node with element X after Insertion,
First step, identify the middle node and assign name PTR to the node,

STCS-TVM : 9496366351

Page 6

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Second step, identify the next node to the key node and assign name NEXT to the node,

Third step, assign PTR link to NEW,

Now PTR pointing to the NEW node.


Final step, assign NEW link to NEXT node,

Now NEW node pointing to NEXT node.


A NEW node at midle position inserted.
The following is the code for the insertion at middle operation:

new = malloc(sizeof(node));
new-> data = X;

New node creation and storing element

new->link = NULL;
ptr = header; /* Pointing to the first node in the linked list */
/* Here key is the value supplied by the user */
while( ptr->data != key)
{
Finding the middle node in
ptr = ptr->link;
the linked list
}

STCS-TVM : 9496366351

Page 7

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

if(ptr = = NULL) /* Reached the end of the linked list */


{
printf(\n A node with key element not found. Insertion not possible);
return;
}
/*Now the ptr pointing to the key node */
next = ptr -> link; /* ptr pointing to next node */
ptr->link = new; /* ptr pointing to new node */
new->link = next; /* new node pointing to next node */
printf(\n Insertion at middle position successfully completed);
2.1.2 Deletion

Removing the existing element from the single linked list. The following are the three
ways of removing the element from the single linked list:

Deletion at begin
Deletion at end
Deletion at middle

2.1.2.1 Deletion at begin

Removing the first node from the single linked list. First node is the HEADER. After
Removing the first node, next node becomes HEADER. The following figures illustrate
this deletion:
A single linked list before removing the first node,

First step, assign name PTR to the first node:

Second step, move the HEADER pointer to the next node:

STCS-TVM : 9496366351

Page 8

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Third step, remove PTR node from the single linked list:

Finally, after removing the first node, the linked list looking like the following:

The following code illustrates the removal of first node from the single linked list:
ptr = header; /* Pointing to the first node in the linked list */
header = header->link; /* Moving the header pointer to the next node */
free(ptr); /* Removing the ptr node from the memory */
2.1.2.2 Deletion at end

Removing the last node from the single linked list. After removing the last node, previous
node becomes last node. The following figures illustrate this deletion:
A single linked list before removing the last node,

First step, assign name LAST to the first node:

Second step, moving the pointer LAST to the last node of the linked list:

STCS-TVM : 9496366351

Page 9

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Third step, Assign name PTR to the previous node of the LAST node:

Fourth step, PTR pointing to NULL :

Fifth step, Remove LAST node from memory:

Finally, after removing the last node, the linked list looking like the following:

The following code illustrates the removal of last node from the single linked list:
last = header; /* Pointing to the first node in the linked list */
while(last->link != NULL)
{
ptr = last; /* moving to the last but one node */
last = last ->link; /* moving to the last node of the linked list */
}
Ptr->link = NULL; / ptr pointing to NULL */
free(last);/* Removing the last node from memory */
2.1.2.3 Deletion at middle

Removing the existing node at the middle position of the single linked list. The following
figures illustrate this deletion:

STCS-TVM : 9496366351

Page 10

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

A single linked list before removing the middle node,

A key element is used to identify middle node. The identified element removed from the
linked list.
First step, assign name MID to the first node:

Second step, moving MID pointer to the position where the key element found in the list.
Let us assume that the key element is B in this case. So, MID pointer moved to the node
where node element matches with key element. Also identify previous node to the MID
node.

Third step, identify and assign name NEXT to the next node of the MID node:

Fourth step, assign NEXT address to the PREV node link:

Fifth step, remove MID node from the memory:

STCS-TVM : 9496366351

Page 11

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Finally, after removing the middle node the linked list looking like the following:

The following code illustrates the removal of middle node from the single linked list:
mid = header; /* Pointing to the first node in the linked list */
while(mid->data != key)
{
prev = mid; /* identifies previous node to the middle node */
mid = mid->link; /* Identifies key node */
}
If(mid = = NULL) /* If key element not found in the list MID reaches NULL */
{
printf(\n Key element not found. Deletion not possible.);
return;
}
next = mid->link; /* Identify next node to the middle node */
prev ->link = next; /* prev node pointing to next node */
free(mid); /* Removing the key node from the memory */
2.1.2 Traversals

Traversal means visiting all nodes in the linked list. Single linked list allows to traverse
from first node to last, but reverse not possible.
First step, assign name PTR to the first node:

Second step, traverse from first node to the last


The following code illustrates the single linked list traversal:
ptr = header; /* Pointing to the first node in the linked list */
while(ptr != NULL) /* visiting all nodes until ptr reaches NULL pointer */
{
Visit(ptr);
ptr = ptr ->link
}
STCS-TVM : 9496366351

Page 12

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Here visit is a function, which processes node element.


2.2 Double linked lists
A double linked list is a linked list, in which each node contains one data part and two
link parts, one link pointing to next node and other pointing to previous node. The
following figure shows double linked list node:

The following figure shows double linked list:

The first node PREV pointer and last node NEXT pointer always pointing to NULL,
indicated no previous node and no next node. The first node identified by HEADER and
last node identified by TAIL.
The following are the double linked list operations:

Insertion
Deletion
Traversal

2.2.1 Insertion

Inserting a new node into the double linked list. The following are the three ways of
inserting a new element into the double linked list:

Insertion at begin
Insertion at end
Insertion at middle

2.2.1.1 Insertion at begin

Inserting a new node at the first position of the double linked list, i.e. the new node
becomes the first node in the linked list. The following figures illustrate this insertion:
A new node with element X before Insertion,

STCS-TVM : 9496366351

Page 13

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

First step, NEW node next pointer pointing to HEADER:

Second step, HEADER node previous pointer pointing to NEW node:

Third step, moving the HEADER pointer to NEW node, so that NEW node becomes first
node in the linked list:

The following is the code illustrates the insertion at begin operation:


new = malloc(sizeof(node));
new-> data = X;
New node creation and storing element

new->prev = NULL;
new->next = NULL
new->next = header; /* new node next pointer pointing to header */
header->prev = new; /* header previous pointer pointing to new node */
header = new; /* Now new node becomes first node in the linked list */
2.2.1.2 Insertion at end

Inserting a new node at the end of the double linked list, i.e. the new node becomes the
last node in the linked list. The following figures illustrate this insertion:
A new node with element X before Insertion,

STCS-TVM : 9496366351

Page 14

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

First step, TAIL next pointer pointing to NEW node:

Second step, NEW pointing to the TAIL node:

Third step, moving TAIL pointer to NEW node.So, the NEW node becomes the last node
in the linked list:

The following code illustrates this insertion:


new = malloc(sizeof(node)); /* Creating a new double linked list node */

new = malloc(sizeof(node));
new-> data = X;
New node creation and storing element

new->prev = NULL;
new->next = NULL
tail->next = new ; /* last node pointing to the new node */
new->prev = tail; /* new node pointing to the last node in the linked list */
tail = new; /* tail moved to new node , so that tail becomes last node in the linked list */
2.2.1.3 Insertion at middle

Inserting a new node into the double linked list at middle position based on the key
element. The following figure illustrates this insertion:

STCS-TVM : 9496366351

Page 15

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Double linked list and new node with element x before insertion at middle position:

First step, Assign name PTR to the first node:

Second step, moving PTR to the one of the middle node based on the key element. Let us
assume that here the middle node with element C matches with key element. So, PTR
moved to the node with element C:

Third step, assign name NPTR to the next node of the PTR node:

Fourth step, NPTR prev pointer pointing to the NEW node:

STCS-TVM : 9496366351

Page 16

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Fifth step, NEW prev pointer pointing to PTR node:

Sixth step, PTR next pointer pointing to NEW node:

Seventh step, NEW next pointer pointing to NPTR:

Finally NEW node successfully inserted into the double linked list at middle position.
2.2.2 Deletion

Removing the existing node element from the double linked list. The following are the
three ways of removing the element from the double linked list:

Deletion at begin
Deletion at end
Deletion at middle

2.2.2.1 Deletion at begin

Removing the first node from the double linked list .The following figures illustrates this
operation:
A double linked list before removing the first node,

First step, Assign name PTR to the first node:

Second step, move the HEADER to the next node:

STCS-TVM : 9496366351

Page 17

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Third step, make prev pointer of HEADER to NULL:

Fourth step, Remove PTR node form the memory,

Finally, the double linked list looking like the following:

The following code illustrates the above operation implementation:


PTR = HEADER; /* Assign name PTR to first node */
HEADER = HEADER->next ; /* move HEADER to next node */
HEADER->prev = NULL; /*make HEADER prev pointer to NULL */
Free(PTR); /* Remove node PTR from the memory */
2.2.2.2 Deletion at end

Removing the last node from the double linked list .The following figures illustrates this
operation:
A double linked list before removing the last node,

First step, Assign name PTR to the last node:

Second step, move the TAIL to the previous node:

STCS-TVM : 9496366351

Page 18

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Third step, assign NULL to the TAIL next pointer:

Fourth step, Remove PTR node form the memory,

Finally, the double linked list looking like the following:

The following code illustrates the above operation implementation:


PTR = TAIL; /* Assign name PTR to last node */
TAIL = TAIL->prev ; /* move TAIL to the previous node */
TAIL->next = NULL; /* assign NULL to the TAIL next pointer */
Free(PTR); /* Remove node PTR from the memory */
2.2.2.3 Deletion at middle

Removing the middle node from the double linked list based on the key element that
identifies the middle node. The following figures illustrate this operation:
A double linked list before removing the last node,

First step, Assign name PTR to the first node:

Second step, moving PTR to the one of the middle node based on the key element. Let us
assume that here the middle node with element C matches with key element. So, PTR
moved to the node with element C:

STCS-TVM : 9496366351

Page 19

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Third step, assign name PPTR to the PTR previous node and assign NPTR to the PTR
next node:

Fourth step, PPTR node next pointer pointing to NPTR node:

Fifth step, NPTR node previous pointer pointing to PPTR node:

Sixth step, Remove PTR node from the linked list:

Finally, the linked list looking like the following:

The following code illustrates the implementation of the above operation:


PTR = HEADER; /* Assign name PTR to first node */
while(PTR->data != key) /* identifying middle node, based on key element */
{
PTR = PTR->next;
}
if(PTR==NULL) /*if key element not present in the list */
{
printf(\n Key element not found.);
return;
}
STCS-TVM : 9496366351

Page 20

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

PPTR = PTR->prev; /* assign name PPTR to PTR previous node */


NPTR = PTR->next; /* assign name NPTR to PTR next node */
PPTR->next = NPTR; /* PPTR node next pointer pointing to NPTR node */
NPTR->prev = PPTR; /* NPTR node prev pointer pointing to PPTR node */
Free(PTR); /* removing node PTR from the memory */
2.2.3 Traversals

Traversal means visiting all nodes in the linked list. Double linked list allows to traverse
from first node to last, and last node to first node, i.e. forward and backward traversals
are possible with double linked list. The following are the double linked list traversals:

Forward Traversals
Backward Traversals

2.2.3.1 Forward Traversals

Visiting nodes from first node to last node.


First step, assign name PTR to the first node:

Second step, Traverse from first node to last node:


The following code illustrates the above operation:
PTR = HEADER; /* Assign name PTR to first node */
while( PTR !=NULL)
{
PTR = PTR->next;/* visiting from first node to last node */
}
2.2.3.2 Backward Traversals

Visiting nodes from last node to first node.


First step, Assign name PTR to the last node:

Second step, Traverse from last node to first node:


The following code illustrates the above operation:
PTR = LAST; /* Assign name PTR to last node */
STCS-TVM : 9496366351

Page 21

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

while( PTR !=NULL)


{
PTR = PTR->prev;/* visiting from last node to first node */
}
3. Stacks
Stack is a data structure, in which elements are inserted and deleted at one end called
TOP. TOP is a pointer always pointing to top of the stack.
Stack is also called LIFO (Last-In First-Out) list, because last inserted element removed
first. (Or) It is also called FILO(First-In Last-Out) list, because first inserted element
removed last.
Like array and linked list stack is a linear data structure. In array or linked list elements
are inserted at any position, but in stacks elements are inserted at one end called TOP.
For example , A stack of bread pieces in a box:

The following are stack operations

PUSH
POP

The elements from the stack are removed in reverse order of their insertion. In case of
item insertion TOP pointer incremented and it is pointing to the newly inserted item. In
case of deletion TOP pointer decremented and it is pointing to the just below the
currently removed item.
The maximum number of elements that accommodate depends on the size of the stack.
Here we assume that the maximum size of the stack is MAXSIZE.

STCS-TVM : 9496366351

Page 22

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

3.1 PUSH operation


Inserting new item into the stack at TOP position. New item inserted into the stack only
when TOP<=MAXSIZE. Otherwise not possible to insert new item into the stack, this
situation is called stack overflow i.e. stack is full.
For example, let us assume that MAXSIZE = 6 and current TOP = 5:
Insert new item piece6 into the stack , TOP<=MAXSIZE is true. So, item is allowed to
insert.
After inserting new item stack looking like the following:

Insert new item piece6 into the stack , TOP<=MAXSIZE is false. So, item insertion not
possible i.e. stack is full called stack overflow.
The following code illustrates the PUSH operation implementation:
void PUSH(int item)
{
if(TOP <= MAXSIZE)
{
printf(\n Stack overflow. Insertion not possible,);
return;
}
Stack[TOP] = item; /* Inserting item into the stack */
TOP++; /* Incrementing the TOP stack ponter */
}
3.1 POP operation
Removing the existing item from the stack. The item removed from the stack only when
TOP>0. Otherwise stack is empty, this situation is called stack underflow i.e. stack is
empty.
For example, let us assume that currently stack contains two items .

STCS-TVM : 9496366351

Page 23

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Now the POP operation is as follows:

To remove item from the stack, it checks TOP>0. It is true. So, it removes item from the
stack. After removing the item the stack looking like the following:

Again remove item from the stack, it checks TOP>0. It is true. So, it removes item from
the stack. After removing the item the stack looking like the following:

Again try to remove item from the stack, it checks TOP>0. It is false. So stack is empty,
no items present in the queue to remove. This status of the stack is called stack under
flow.
The following code illustrates the POP operation implementation:
int POP(void)
{
int x;
if( TOP < 0)
{
printf(\n Stack Underflow.);
return -1; /*indicates stack underflow*/
}
x = stack[TOP]; /* Taking item from the stack */
TOP--; /* Decrementing stack pointer TOP */
}
4. Queues
A Queue is a linear data structure, in which elements are inserted at one end called REAR
and deleted at one end called FRONT.

STCS-TVM : 9496366351

Page 24

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Queue is also called FIFO (First-In First-Out) list, because first inserted element removed
first. (OR) It is also called LILO(Last-In Last-Out) list , because last inserted removed
last.
Stack and Queue both are ordered collection of homogeneous elements .Only the
difference in inserting and removing element. In stack elements are inserted at one end
called TOP, where as in Queues the elements are inserted at one end called REAR and
elements are removed at one end called FRONT.
For example, a number of persons waiting in front of the counter to get the ticket to
watch a movie. The persons are served in the order their arrival time, i.e. a person who
comes first will get ticket first.

The following are the Queue operations:

Insertion
Deletion

The elements from the queue are removed in the order of their insertion. In case of item
insertion REAR pointer incremented and it is pointing to the newly inserted item. In case
of deletion FRONT pointer incremented and it is pointing to the next immediate element
in the queue.
The maximum number of elements that accommodate depends on the size of the queue
Here we assume that the maximum size of the queue is MAXSIZE.
4.1 Insertion
Inserting a new element into the queue at REAR position. New item inserted into the
queue only when REAR is not equal to MAXSIZE. If REAR equal with MAXSIZE then
insertion not possible, because queue is full.
For example, let us assume that the queue size MAXSIZE = 3, and FRONT=0 and REAR
= 0.

STCS-TVM : 9496366351

Page 25

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Insert item A into the queue. Initially the empty queue is looking like the following:

Compare REAR= =MAXSIZE. In this case it is false, because MAXSIZE=3 and


REAR=0. So, insertion possible. After insertion queue looking like the following:

Insert item B into the queue. Compare REAR= =MAXSIZE. In this case it is false,
because MAXSIZE=3 and REAR=1. So, insertion possible. After insertion queue looking
like the following:

Insert item C into the queue. Compare REAR= =MAXSIZE. In this case it is false,
because MAXSIZE=3 and REAR=2. So, insertion possible. After insertion queue looking
like the following:

Insert item D into the queue. Compare REAR= =MAXSIZE. In this case it is true,
because MAXSIZE=3 and REAR=3. So, queue is full insertion not possible.

STCS-TVM : 9496366351

Page 26

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

The following code illustrates the queue insertion operation implementation:


Assume that the queue is an array to store elements.
void insertion(int item)
{
if(rear = = MAXSIZE)
{
printf(\nQueue is Full. Insertion not possible);
return;
}
if( rear == 0 && front == 0)
{
front = 1;
}
rear++;
queue[rear] = item;
}
4.1 Deletion
Removing the existing element from the queue at FRONT position. Item removed from
the queue only when FRONT is not equal to 0. If FRONT is equal to 0, then queue is
empty . So, removing the existing item from the queue is not possible.
For example, let us assume that the queue size MAXSIZE = 3, and FRONT=1 and REAR
= 3.

Remove item A from queue. To remove the item from the queue first check the condition
FRONT=0. In this case it is false. So, queue is not empty , deletion possible. Check one
more condition FRONT = REAR , in this case it is false i.e. FRONT not reached end of
the queue.

Remove item B from queue. To remove the item from the queue first check the condition
FRONT=0. In this case it is false. So, queue is not empty , deletion possible. Check one
more condition FRONT = REAR , in this case it is false i.e. FRONT not reached end of
the queue. After removing the item, queue is looking like the following:
STCS-TVM : 9496366351

Page 27

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Remove item C from queue. To remove the item from the queue first check the condition
FRONT=0. In this case it is false. So, queue is not empty , deletion possible. Check one
more condition FRONT = REAR , in this case it is true i.e. FRONT reached end of the
queue. To reuse the queue set FRONT=0 and REAR=0. After removing the item, queue
is looking like the following:

Now try to remove item from the queue, in this case FRONT = 0. So, queue is empty and
deletion not possible.
The following code illustrates the queue deletion operation implementation:
Assume that the queue is an array to store elements and this code returns -1 if queue is
empty, otherwise it return deleted item from the queue.
int deletion(void)
{
if( front = = 0)
{
printf(\nQueue is empty. Deletion not possible);
item = -1;
}
item = queue[front];
if(front= =rear)
{
front=rear=0;
}
else
{
front++;
}
return (item);
}

STCS-TVM : 9496366351

Page 28

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

4. Trees
A tree is a non-linear data structure, in which elements are organized in hierarchical
manner with one parent and many children.
Let us define a tree. A tree is a set of nodes arranged in hierarchical manner with the
following properties:
1. A tree has a unique node called root
2. The remaining nodes are divided into one or more sub-trees.
This is the recursive definition. Each sub tree is again a tree.

Here tree T is divided into three sub-trees T1, T2 and T3. Again T1 divided into T11 and
T12 and so on.
4.1 Terminology
Root: A root is the special node , which is used to identify the tree. There is only path
from root node to every node
Node: Node is used to store tree element.
Parent: Immediate predecessor of a node. Every node in the tree has a parent except to
the root node.
Child: Immediate successor of a node.
Siblings: Child nodes with same parent.
Leaf node: A node which has no child nodes.
Degree: Maximum number of child nodes to a node.
Path: A path is the sequence of nodes which connected with edge.
Edge: Edge connects two nodes. Edge is also called link.
Level: Length of the path from root node to the node. Root has level 0.
Height: Maximum number of nodes possible from from root node to leaf node.
Internal node: A node with at least one child node. Internal nodes are also called nonterminal nodes.
External node: Leaf nodes are called external nodes. External nodes are also called
terminal nodes.

STCS-TVM : 9496366351

Page 29

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

4.2 Binary trees


A binary tree is a set of nodes with the following properties:
1. A tree has a unique node called root.
2. Remaining nodes are divided into two sub-trees called left-sub-tree and right-subtree. Each node has at most two child nodes, i.e. each node has zero or one or two
child nodes.

The following are the various binary trees:

The following is the binary tree for the mathematical expression (a*b)+(c/d):

Maximum number of nodes in a binary tree at level L = 2L. Maximum number of nodes in
a binary tree with height H = 2H-1. Number of nodes in a binary tree = Number edges in a
binary tree + 1
The node of a binary tree is represented by the following data structure:

LCHILD is a pointer points to left child of a node and RCHILD is a pointer points to
right child of a node.
If LCHILD=NULL then node has no left child. If RCHILD=NULL then node has no
right child.
The mathematical expression (a*b)+(c/d) is represented using the binary tree node
structure in the following way:

STCS-TVM : 9496366351

Page 30

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

4.3 Binary Search Tree


A binary search tree is a binary tree with the property, the value of any node is greater
than its left child node value and less than its right child node value.
Let us construct the binary search tree with the following list of values:
42

65

29

14

53

79

Insert 42 into the binary search tree. Initially tree empty, so 42 becomes the root node of
the binary search tree.

Insert 65 into the binary search tree, 65 is greater than 42, so 65 becomes the right child
of 42.

Insert 29 into the binary search tree, 29 is less than 42, so 29 becomes the left child of 42.

Insert 14 into the the binary search tree, 14 is less than 42, again it is compared with the
value 29 , 14 is less than 29. So 14 becomes left child of 29.

STCS-TVM : 9496366351

Page 31

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Insert 53 into the the binary search tree, 53 is greater than 42, again it is compared with
the value 65 , 53 is less than 65. So 53 becomes left child of 65.

Insert 79 into the the binary search tree, 79 is greater than 42, again it is compared with
the value 65 , 79 is greater than 65. So 79 becomes right child of 65.

The following are the binary search tree operations:

Searching
Insertion
Deletion
Traversals

4.3.1 Searching

Finding the binary search tree node element based on the key item. Searching begins with
the root node and the pointer moving through the path in the following way:
If the key item is less than any node, then the pointer moved to left child of the current
node, otherwise the pointer is moved to right child of the current node. If it is matched
with the key item then search is successful. If the pointer reached the NULL pointer then
search is unsuccessful.
The following code illustrates this operation:
enum bool{false,true};
bool search(struct node *root, int key)
{
struct node *ptr;
ptr = root;
while(ptr !=NULL)
{
if(ptr->data==key)
return true;
else if(ptr->data < key)
STCS-TVM : 9496366351

Page 32

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

ptr = ptr->lchild;
else
ptr = ptr->rchild;
}
if(ptr==NULL)
return false;
}
4.3.2 Insertion

Inserting a new node into the binary search tree. The new item is searched starting from
the root. If the new item found in the binary search tree then the new item is duplicate
node, then no need to insert the new item into the binary search tree, because duplicate
nodes are not allowed into the tree.
If new item not found in the binary search tree, then pointer reaches the NULL pointer.
So, search ends here. Now insert new item at the leaf node where search completed. If
leaf node value is greater than new item then the new item becomes left child of the leaf
node, otherwise the new item becomes right child of the leaf node.
For example, insert new item 31 into the following binary search tree,
Before insertion the binary search tree is looking like the following:

New item 31 compared with 42, 31 is less than 42, again it is compared with the value 29
, 31 is greater than 29. So 31 becomes right child of 29
Here 29 is the leaf node and 31 not found in the tree. Finally 31 compared with 29 and it
is greater than 29. So, 31 becomes the right node of the 29.
After insertion tree is looking like the following:

The following code illustrates this operation:


void insert(struct node *root, int item)
{
struct node *ptr;
struct node *parent;
STCS-TVM : 9496366351

Page 33

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

struct node *new;


new = malloc(sizeof(struct node));
new->data = item;
new->lchild = new->rchid = NULL;
ptr = root;
while(ptr!=NULL)
{
parent = ptr;
if(ptr->data > item)
ptr = ptr->lchild;
else if(ptr->data < item)
ptr = ptr->rchild;
else
{
printf(\nDuplicate node element.);
return;
}
}
if(parent->data>item)
parent->lchild = new;
else
parent->rchild = new;
}
4.3.3 Deletion

Removing the existing node from binary search tree. First, the deleted item searched in
the tree. If the node found in the tree , it is removed from the tree.
There are three cases in deleting the node from the binary search tree.
Let us assume that the deleted node name PTR,
Case 1: PTR is the leaf
Case 2: PTR has one child
Case 3:PTR has two childs
4.3.3.1 Case 1

The node PTR removed from the binary search tree by simply replacing the pointer from
parent of PTR to PTR with NULL.
For example, removing the node 31 from the binary search tree. Here 31 is leaf node.
Parent of 31 is 29. The link between 29 and 31 removed .

STCS-TVM : 9496366351

Page 34

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

After deletion the tree is looking like the following:

4.3.3.2 Case 2

The node PTR is replaced with the child node of the PTR node.
For example, consider the following binary search tree:

In the above tree 29 has only child .Let us remove this node , because this is belongs to
case 2. Node 29 has no right child , so 29 node replaced with the node 14. After deleting
the node the tree is looking like the following:

4.3.3.3 Case 3

The node PTR is deleted from the tree with the following steps:

STCS-TVM : 9496366351

Page 35

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

1. First delete inorder successor of PTR node


2. Replace PTR data value with the inorder successor of PTR node value
Here, inorder successor of the PTR is the right childs left most node of the PTR.
For example, consider the following binary search tree:

Step 1: Inorder successor of the PTR is 71. First delete this node from the tree. After
removing the inorder successor of PTR node, the tree is looking like the following:

Step 2: Replace PTR node value with inorder successor node value. After replacing the
node value , tree is looking like the following:

STCS-TVM : 9496366351

Page 36

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

The following code illustrates the deletion operation:


void delete(struct node *root, int key)
{
struct node *ptr=root;
struct node *parent, *ptr1;
int x;
while(ptr != NULL)
{
parent = ptr;
if(key < ptr->data)
ptr = ptr->lchild;
else if(key > ptr->data)
ptr = ptr->rchild;
else
break;
}
if(ptr == NULL)
{
printf(\nKey element not found.);
return;
}
if(ptr->lchild == NULL && ptr->rchild == NULL) /* Case 1*/
{
if(parent->lchild == ptr)
parent->lchild = NULL;
else
parent->rchild = NULL;
}
else if(ptr->lchild != NULL && ptr->rchild == NULL) /* Case 2*/
{
if(parent->lchild == ptr)
parent->lchild = ptr->lchild;
else
parent->rchild = ptr->lchild;
}
else if(ptr->lchild == NULL && ptr->rchild != NULL) /* Case 2*/
{
if(parent->lchild == ptr)
parent->lchild = ptr->rchild;
else
parent->rchild = ptr->rchild;
}
else
{
ptr1 = insucc(ptr);
x = ptr1->data;

STCS-TVM : 9496366351

Page 37

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

delete(root,x);
ptr->data = x;
}
}
The following code illustrates the inorder successor of a node:
struct node* insucc(struct node *p)
{
struct node *ptr;
ptr = p->rchild;
while(ptr !=NULL)
{
ptr = ptr->lchild;
}
return (ptr);
}
4.3.4 Traversals

Traversals means visiting all nodes in the tree. There are three ways of visiting all node in
the tree.

Inorder
Preorder
Postorder

The following binary used to illustrate binary traversals:

4.3.4.1 Inorder

The inorder tree traversal uses the following steps:


1. Travere left sub-tree
2. Visit root node
3. Travers right sub-tree

STCS-TVM : 9496366351

Page 38

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

The inorder tree traversal of the above binary tree shown below:
14

42

53

71

79

93

The following is the code for the inorder tree traversal:

void inorder(struct node *ptr)


{
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf(%d,ptr->data);
Inorder(ptr->rchild);
}
}
4.3.4.2Preorder

The inorder tree traversal uses the following steps:

1. Visit root node


2. Travere left sub-tree
3. Travers right sub-tree
The preorder tree traversal of the above binary tree shown below:
42

14

71

53

79

93

The following is the code for the preorder tree traversal:


void preorder(struct node *ptr)
{
if(ptr!=NULL)
{
printf(%d,ptr->data);
preorder (ptr->lchild);
preorder (ptr->rchild);
}
}
4.3.4.3Postorder

The postorder tree traversal uses the following steps:


1. Travere left sub-tree
2. Travers right sub-tree
3. Visit root node

STCS-TVM : 9496366351

Page 39

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

The postorder tree traversal of the above binary tree shown below:
14

53

93

79

71

42

The following is the code for the postorder tree traversal:


void postorder (struct node *ptr)
{
if(ptr!=NULL)
{
printf(%d,ptr->data);
postorder (ptr->lchild);
postorder (ptr->rchild);
}
}
5. Graphs
A Graph is a non-linear data structure, in which elements are organized in hierarchical
manner with many parents and many children.
Formally, a graph G=(V,E)
Where V = Set of nodes(or Vertices) and E = Set of edges (or arcs)
Edge connects two vertices. Generally, there are two types of graphs

Directed graph
Un-directed graph

5.1 Directed graph


A directed graph G=(V,E), there is an edge (Vi,Vj) (Vj,Vi)
The following is the directed graph G=(V,E),

Here V={A,B,C,D,E,F} and


E={(A,B),(B,D),(B,E),(C,A),(D,F),(E,D),(E,F)}
5.2 Un-directed graph
An un-directed graph G=(V,E), there is an edge (Vi,Vj) = (Vj,Vi)
The following is the un-directed graph G=(V,E)

STCS-TVM : 9496366351

Page 40

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

Here V = {A,B,C,D,E,F} and


E={(A,B),(A,C),(B,D),(B,E),(D,E),(D,F)}
5.3Terminology
Graph: A graph is a set of nodes and a set of edges.
Edge: A edge is an arc, which connects two nodes.
Digraph: A digraph is the directed graph.
Path: A path is the sequence of edges from one vertex to another.
Degree of vertex: The number of vertices connected to this vertex.
Weighted graph: A weight(or Value) is assigned to the each edge of a graph.
5.4 Matrix representation of graph
Adjacency matrices are used to represent graphs. An adjacent matrix is square matrix of
size n x n .Here n is the number of vertices.
If there is an edge from vertex vi to vertex vj , then the matrix element is 1, otherwise the
matrix element is 0.
1 if there is an edge from i to j
i.e.

aij =
0 otherwise

The adjacent matrix A is shown below:

STCS-TVM : 9496366351

Page 41

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

For example , consider the following graph:

The adjacent matrix for the above graph is shown below:

5.5 Graph Traversals


Traversal means visiting all nodes in the graph.
There are two types graph traversals:

Depth First Search(DFS)


Breath First Search(BFS)

5.5.1 Depth First Search


In Depth First Search , first select one vertex to start visit, then select any one of the
adjacent vertices which are not visited ,and again select any one of the adjacent vertices
which are not visited and soon.
For example consider the following graph:

Select first vertex A, adjacent to A={B,C},select B and find adjacent to B={D,E}, select
D and find Adjacent to D={F} and soon.
DFS Traversal = A,B,D,E,F,C
DFS traversals uses stack data structure to visit all nodes in graph.
The following code illustrates DFS graph traversals:

STCS-TVM : 9496366351

Page 42

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

#define MAXSIZE 100


enum bool{false,true};
int stack[MAXSIZE];
int TOP = 0;
void DFS(int g[MAXSIZE][MAXSIZE], int v, int n)
{
int *visited;
int i;
visited = malloc(n*sizeof(int));
for(i=1;i<=n;i++)
visited[i] = false;
stack[TOP++] = v;
visited[v] = true;
while(TOP>0)
{
v=stack[TOP--]
printf(%d,v);
for(i=1;i<=n;i++)
{
if(g[v][i]= =1 && !visited[i])
stack[TOP++] = i;
visited[i] = true;
}
}
for(i=1;i<=n;i++)
if(visited[i] = = false)
DFS(g,i,n);
}
5.5.2 Breath First Search
In Breath First Search , first select one vertex v to start visit, then select all vertices
adjacent to v , then select adjacent vertices which are not visited to the adjacent vertices
of v. This process repeated until all vertices visited.
For example consider the following graph:

Select first vertex A, adjacent to A = {B,C}, then select nodes which are adjacent
to{B,C} ={D,E} and ,then select adjacent to {D,E}={E}. This ends Breath First Search.
BFS Traversal = A,B,C,D,E,F

STCS-TVM : 9496366351

Page 43

DATA-STRUCTURES-AND-ALGORITHMS

CS-2011

BFS traversals uses queue data structure to visit all nodes in graph.
#define MAXSIZE 100
enum bool{false,true};
int queue[MAXSIZE];
int FRONT=0,REAR=0;
void BFS(int g[MAXSIZE][MAXSIZE], int v, int n)
{
int *visited;
int i;
visited = malloc(n*sizeof(int));
for(i=1;i<=n;i++)
visited[i] = false;
if(FRONT==0 && REAR==0)
FRONT=1;
REAR++;
queue[REAR] = v;
visited[v] = true;
while(FRONT!=0)
{
v = queue[FRONT];
printf(%d,v);
if(FRONT == REAR)
FRONT=REAR=0;
else
FRONT++;
for(i=1;i<=n;i++)
{
if(g[v][i]= =1 && !visited[i])
{
if(FRONT==0 && REAR==0)
FRONT=1;
REAR++;
queue[REAR] = i;
visited[i] = true;
}
}
}
for(i=1;i<=n;i++)
if(visited[i] = = false)
BFS(g,i,n);
}

STCS-TVM : 9496366351

Page 44

Вам также может понравиться