You are on page 1of 28

Unit-V-Data Structures

Page 1 of 28

DATA STRUCTURES
Definition: Data may be organized in many different ways. The logical (or)
mathematical model of a particular organization of a data is called data
structure. The following are the various data structures:
1) Stacks, 2) Queues, 3) Linked List, 4) Trees, 5) Graphs
Stacks, queues and linked list are called linear data structures. Trees and
graphs are called non-linear data structures.
Stacks: A stack is a linear list (data structures) in which all insertions and
deletions of entries are made at same end. This end is called TOP. The other
end is called BOTTOM.
EX: A stack of dishes, a stack of books, coins etc.
In a stack an item may be added (or) removed only from the top of the stack
i.e. last element to be inserted into the stack will be the first to be removed.
For this reason stacks are called LAST IN FIRST OUT (LIFO) lists. The
following diagram shows a stack with five elements.

Stack Operations: Initially the operations on the stack are simulated by


using a vector consisting of some (large) number of elements. The
representation of such an allocation scheme is as follows:

A pointer TOP is used to specify the top element of the stack. Initially
when the stack is empty, TOP has a value of -1. When the stack contains a
single element, top has a value of zero and so on. Each time a new element is
inserted into the stack the pointer is incremented by 1. The pointer is
decremented by 1 each time a deletion is made from the stack.

Stack Operations
Basically, there are two operations performed on the stack.
Push: Push is the term used to insert the element on the top of stack.
Pop: Pop is the term used to delete the elements from top of the stack.
Algorithm: PUSH(S, TOP, X): this algorithm inserts the elements.
Step: 1 [check for the stack over flow]
If (top>max) then write (stack over flow)
Return

Honey Creations

Unit-V-Data Structures
Page 2 of 28

Step: 2 [increment top by 1]


Top

top+1

Step: 3 [insert element]


S[top]

Step: 4 [finished]
Return
Algorithm: pop(s, top, x): [this algorithm deletes the top element from the
stack]
Step: 1 [check for the stack under flow]
If (top=-1) then write (stack underflow)
Return
Step: 2 [assign top element to x]
X

s[top]

Step: 3 [decrement top by 1]


Top

top-1

Step: 4 [finished]
Return

QUEUES:
A queue is a linear list in which additions and deletions take place at
different ends. The end at which new elements are added is called REAR and
from which old elements are deleted is called FRONT. Queues are also called
First in First out Lists (FIFO). The order in which an element is entered in a
queue is the order in which they leave queue. This is also called First Come
First Serve (FCFS) lists.

Ex: The people waiting in a line from a queue where the first person in a line is
the first person to be processed.
Queues may be represented in computer memory in various ways, usually by
means of one way lists (or) linear arrays. Each of the queues will be
maintained by a linear array queue and two variables. F containing the
location of the first element of the queue and R containing the last element
of the queue. The condition F=-1 will indicate that the queue is empty.
Whenever an element is deleted from the queue the value of F is incremented
by 1 and whenever an element is added into the queue the value of R is
incremented by 1.
Queue Operations:
There are mainly two operations that can be performed on queue. They are:

Honey Creations

Unit-V-Data Structures
Page 3 of 28

1. Q.insert: inserts a data item in a queue.


2. Q.delete: deletes the first element from the queue.
Considered an example where the size of the queue is four elements:
Algorithms:
Algorithms 1: Q.insert (Q,F,R,X): [ Given F,R are pointers to the first
and last elements of the queue Q. Q consisting of maximum element
initially F & R have been set to -1]
Step: 1 [check for overflow]
If (R>max) then write queue overflow
Return
Step: 2 [increment R]
R
R+1
Step: 3 [insert x at R in queue]
Q[R]
x
Step: 4 [if F property set]
If (F=-1) then F 0
Step: 5 [finish]
Return
Algorithm 2: Q.DELETE (Q, F, R, X): [Q is a queue represented in
memory for F and R are two variables are first and last elements in a
queue. This algorithm deletes and assigns the first element of the queue
to the variable x]
Step: 1 [check underflow]
If (F==-1) then write (queue underflow)
Return
Step: 2 [assigns the deleted value to x]
X
Q[x]
Step: 3 [updates F pointer]
If (F==R) then F
-1
[set F and R values to -1]
R
-1
Else
F
F+1[increment F value by 1]
Step: 4 [finish]
Return

Circular Queue:
Let us have an array A that contains n elements in which A[1] comes just
after A[n]. When this technique is applied to construct a queue it is called
circular queue.
(Or)
Circular queue is a linear list represented in memory, in which additions
and deletions takes different ends (rear and front). The elements in a circular
queue cq[0],cq[1], . . . ,cq[n-1] are arranged in a circular fashion with cq[0]
followed by cq[n-1].
Consider an example of circular queue that contains a maximum of 5
elements. A diagram of circular queue contents is shown below:

Circular Queue Operations:

Honey Creations

Unit-V-Data Structures
Page 4 of 28

Cq insert: Which insert an element into a circular queue.


Cq delete: Which deletes an element from the circular queue.
Circular queue operations are shown in below diagrams:

Algorithm: 1:- CQ INSERT (Q, F, R, X):- [given F, R are pointer to the first and
last elements of a circular queue consisting of max+1 elements. This
algorithm inserts x at the rear (R) of the queue. Initially F,R are set to -1]
Step: 1 [check for overflow]
If ( ((R+1) % (MAX+1) ) )=F) then write ( C QUEUE overflow )
Return
Step: 2 [increment R]
R
( (R+1)%(MAX+1))
Step: 3 [insert element]
Q[R]
X
Step: 4 [if F properly set]
If(F=-1) then F
0
Step: 5 [finish]
Return
Algorithm: 2 CQ DELETE (Q, F, R, X):- [given F, R are pointers to the first
and last elements of a circular queue consisting of max+1 elements. This
algorithm deletes the front [F] element of the queue and places it into variable
x]
Step: 1 [check for underflow]
If (F=-1) then write (CQ underflow)
Return
Step: 2 [assign F element to X]
X
Q[F]
Step: 3 [update F pointer]
If (F==R) then F
R
-1
Step: 4 [finish]
Return
DEQUE (DOUBLE ENDED QUEUE):
A deque is a linear list in which the elements can be added (or) removed at
either ends but not in the middle.

Honey Creations

Unit-V-Data Structures
Page 5 of 28

There are two types of DEQUE:


1. Input restricted DEQUE: Input restricted DEQUE is a deque which allows
insertions at only one end of the list (REAR), but allows deletions at both
ends of the list.
2. Output restricted DEQUE: Output restricted DEQUE is a deque which
allows deletions at only one end of the list (FRONT), but allows insertions at
both ends of the list.
PRIORITY QUEUES: The priority queue is a collection of elements such that
element has been assigned a priority such that the order in which the
elements are deleted and processed comes from the following rules:
1. An element of higher priority is processed before any element of lower
priority.
2. Two elements of the same priority are processed according to the order in
which they were added to the queue.
An example of priority queue is a time sharing system: programs of high
priority are processed first and programs with same priority from a standard
queue.
Array Representation Of Priority Queues:
Priority queues are maintained in memory as separate queues for each
level of priority. Each such queue will appear on its own circular array and
must have is own pair of pointers front and rear. A two dimensional array
queue can be instead of linear arrays.
The following diagram represents a priority queue

Front [K] and Rear [K] contains the front and rear elements of row k of
queue, the row that maintains the queue of elements with priority number K.
Difference between stacks and queue
Stack
Queue
1) A stack is a linear list of elements In (1) queue is a linear list in which
which the elements are added (or) elements are added at one end called
removed at the same end Called top
rear and deleted at other end called
front
(2)
In stacks, the elements which is (2) In queues, the element which is to
Inserted last in first to be removed
inserted first
is to be removed.
(3)
Stacks are last in first out (LIFO)
(3) Queues are first in first out (FIFO)
(4)
In stacks, the elements are
Removed in the reversed order
Of
which they are inserted
(5)Suppose the elements A,B,C,D,E are
inserted into a stack, then the deletion
of these elements will be E,D,C,B,A

(4) In queues, elements are removed


in the same order in which they are
added to the queue
(5). Suppose the elements A,B,C,D,E
are added to the queue, then the
deletion of these elements will be
A,B,C,D,E
(6)In stack, we require only one Pointer 6). In queues, we require two pointer
variable top
front and rear

Honey Creations

Unit-V-Data Structures
Page 6 of 28

(7)In stacks, inserting and Deleting elements 7. In queues, inserting elements are
are known as push and pop known as q insert and q delete
operations.

LINKED LIST
A linked list is a linear collection of data elements called nodes. In linked
lists the linear order is given by means of pointers .i.e., each node is divided
into two parts. The first part contains the information of elements (data) and
the second part called the link field contains the address of the next node in
the list.
Node Structure:

There are several kinds of linked lists which are available. They are 1. Linear
linked list, 2. Circular linear list.
1. Linear linked list: In linear linked list, the nodes are linked together in
same sequential manner.

2. Circular linear list: In this lists, the first node address is placed in a linked
field of last node.

Linked list with multiple pointers (Double linked list): These list permits
forward and backward travellers through the lists.

Trees: In trees, nodes are arranged in hierarchical structure.

SINGLE LINKED LIST:


Memory allocation and garbage collection:
Maintenance of linked list in memory means inserting and deleting
nodes from the linked list in memory. A special list is maintained in memory
which contains the un-used memory cells. This list has its own pointer which is
called the list of available space of free storage (unit) list (or) the availability
list (or) the availability stack. Some memory space becomes re-usable when
node is deleted from the list. The operating system of a computer periodically

Honey Creations

Unit-V-Data Structures
Page 7 of 28

collects all the deleted space into free storage list. This technique is called
garbage collection. Garbage collection usually takes place in two steps:
1) It marks all the unused cells.
2) It collects all the marked cells into free storage list.

Traversing a linked list:


In a linked list, each node contains data and link fields. START is a
pointer variable pointing to the first node of the list. Traversing a linked list
means applying some operations to the each node (or) deleting all the nodes
in a sequential manner.
Algorithm: TRAVERSE ( )
[This algorithm traverses a linked list list and applies an operation process
to each element of the list. The variable PTR points to the node currently
being processed.
Step: 1 [initialize pointer PTR]
PTR=START
Step: 2 repeat step 3 and step 4 while (PTR != NULL)
Step: 3 apply process to PTR-data
Step: 4 PTR=PTR-LINK [end of slope loop]
Step: 5 exit

INSERTING AN ELEMENT INTO LINKED LIST


The following algorithm will insert the node into the linked list at a specified
position.
Algorithm: INSERT(list, start, avail, item, pos)
[This algorithm inserts a new node into the linked list at a position given by
pos. the value of the inserted node is available in item. start is the
pointer variable which points to the first node of the linked list. Each node in
the list contains two fields. Data and link avail is a pointer to the top
element of the availability stack. N, PTR are the pointer variable of type node]
Step: 1 [over flow]
If [AVAIL=NULL]
a. Write ( availability stack is empty)
b. Exit.
Step: 2 [remove the first node from AVAIL list and start it in N]
N=AVAIL
AVAIL=AVAIL>LINK
Step: 3 [initialize new node N]
N-data=item
Step: 4 [inserting at starting of the list]
If (pos-1) then

Honey Creations

Unit-V-Data Structures
Page 8 of 28

a. N-LINK=START
b. START=N
c. Exit
Step: 5 [initialize PTR to search]
PTR=START
Step: 6 [find the previous node address]
Repeat for i=1 to pos-2 do
a.
b.
1.
2.

PTR=PTR-LINK
If(PTR=NULL) then
Write ( Invalid position )
Exit

Step: 7 [insert the new node N]


N-LINK=PTR-LINK
PTR-LINK=N
Step: 8 Exit

DELETING AN ELEMENT FROM THE SINGLE LINKED LIST:The following algorithm will delete an element from single linked list in a
specified position.
Algorithm: DELETE (list, start, avail, pos)
[This algorithm deletes a node in the single linked list at a position given by
pos. list is a linked list in a memory whose nodes contains data and link
fields. start is a pointer variable, which points to the first node in the linked
list. avail is a pointer variable which points to the first free node in the
availability list. P,PTR are temporary variables of type node]
Step: 1 [under flow]
If (START=NULL) then
a. Write ( list empty-cannot delete)
b. Exit.

Honey Creations

Unit-V-Data Structures
Page 9 of 28

If(pos=1) then
a. P=START
b. START=START-LINK
c. Goto step7
Step: 3 [initialize PTR to search]
PTR=START
Step: 4 [find the previous node address of the node to be deleted]
Repeat for i=1 to pos-2, do
a. PTR=PTR link
b. If (PTTR=NULL) then
1. Write (invalid position)
2. Exit.
Step: 5 [save the deleted address in p]
P=PTR-link
Step: 6 [delete the node]
PTR-LINK=P-LINK
Step: 7 [return deleted node to avail list]
p-link=avail
avail=p
Step: 8 [exit]

Difference between arrays and linked list:


Arrays

Linked List

1. Arrays are used in the case of


predictable storage requirements i.e.,
the exact amount of data storage
required by a program can be
determined at the time of program
writing.

1. linked lists are used in the case of


requirements
of
un-predictable
storage i.e. the exact amount of data
storage required by a program cannot
be determined easily at the time the
program is writing

2. In arrays the operations such as 2. In linked list operations such as


Insertions and deletions are done In an insertions and deletions are done in
efficient manner.
more efficient manner.
3. The insertions and deletions are
done only by changing the pointers.

3. The insertions and deletions are done


by
moving the elements 4. Successive elements need
either up (or) down.
occupy adjacent space memory.
4.

Successive elements occupy


adjacent space memory.

not

5. In linked list each location contains


data and pointers to the next element
in memory.

5. In arrays, each location contains the


data only.
6. The linear relationship b/w the

Honey Creations

Unit-V-Data Structures
Page 10 of 28

6. The linear relationship b/w the data data elements of a linked list is
elements of an array Is reflected by the reflected by the link of field of
the
physical relationship of the data in node.
memory.
7. In linked list there is no need of such
7. In array, declaring a block of memory thing.
space is reserved.
8. In linked list a pointer is stored
8. There is no need of storage for along with data elements.
pointer (or) links.
9. The conceptual view of linked list
9. The conceptual view (memory map)
of an array.

10. In arrays the address of the First 10. The linked list the address of the
element (base element) is stored in the first node is stored in another variable
called start
array variable.

Double linked list (or) two way linked list:


In certain applications it is desirable that the list be transferred forward
(or) backward direction. This property of linked list implies that each node
must contain two link fields. The link fields are used to denote the predecessor
and successor nodes. The link denoting the predecessor of a node is called
left pointer list and the link denoting the successor of a node is called right
pointer list. This type of list is called a double linked list (or) two way linked
list. The node structure of a double linked list is as follows.

Left pointer contains the address of the previous node, right pointer contains
the address of the next node and data contains the actual information of the
node.

In the above diagram, left end and right end are two pointer variables which
contain the address of the first node and last node respectively.
Inserting the node into double linked list (insertion):
Let list be a double liked list with successive nodes A & B as shown below:

Suppose a node N is to be inserted into a linked list between the nodes A and
B.

Honey Creations

Unit-V-Data Structures
Page 11 of 28

After insertion, in the new list the right pointer of a point to the node N, left
pointer of the node N points to the node A. The right pointer of the node N
points to the node B and left pointer of node B points to the node N.
Deleting a node from double linked list (deletion):
Let list be a double linked list that contains the node N between the nodes A
and B as shown below:

Suppose the node N is to be deleted from the list. DLL (double linked list) of
the deletion is as follows.

Differences between single linked list and double linked list


SINGLE LINKED LIST

DOUBLE LINKED LIST

1. In SLL the list will be traversed 1. In DLL the list will be traversed in
in only one way i.e., in two ways either in forward (or)
forward
direction.
Backward directions.
2. In SLL the node contains only
one link field.
3. The conceptual view (a logical
organisation) of SLL is:

2. In DLL each node contains two Link


fields.
3. The conceptual view (a logical
organization) of a DLL is:

4. Every node contains the address


4. Every node contains the address of
of next node.
next node as well as the address of the
previous node.
5. The node structure in still is as
follows:
6. In SLL the first node address is 5.The node structure of DLL is as
stored in a special pointer
follows
variable START
6. In DLL the first node address is
stored in left end and last node
7. Two linear arrays are requiredto
represent a single linked list in address is stored in right end pointer
variables.
memory.
7. Three linear arrays are required to
represent a double linked list in
memory.

Honey Creations

Unit-V-Data Structures
Page 12 of 28

TREES
Definition: A tree is a finite set of one (or) more nodes such that,
1. There is a specially designated node called root.
2. The remaining nodes are partitioned into n>0 disjoint sets t1,t2.tn.
where each of these sets in a tree t1,t2..tn are called the sub-trees of
the root.

Node:

Honey Creations

Unit-V-Data Structures
Page 13 of 28

A node stands for the item of information on the branches to the other
items. Consider a tree in the above diagram which contains 13 nodes. Each
item of data is a single alphabet.
The root is A and the tree will be drawn from the root node.
(a) Degree: The no of sub-trees of a node is called its degree. The degree
of A is 3, degree of C is 1, degree of M is 0.
(b) Leaf (or) terminal nodes: The nodes that have degree zero are called
leaf (or) terminal nodes. K,L,F,G,I,J,M are leaf nodes.
(c) Non-terminal nodes: The nodes having degree non-zero are called
non-terminal nodes. A, B, C, D, E, H is non-terminal nodes.
(d)Children and parent: Every node in the tree can have some children
nodes. Each child node can also have children and so on. A node that has
a child is called the parent node. The children of D are H, I, J. the
parent of D is A.
(e) Siblings: Children of the same parent are called siblings.
For example H,I,J are siblings. The same terminology can be
extended i.e., the grand parent of M is D.
(f) Ancestors: Ancestors of a node are all the nodes in the path from the
root to that node. Ancestors of M are A, D, H.
(g) Degree of a tree: The degree of a tree is a maximum degree of the
node in a tree. The tree in the diagram has the degree 3.
(h) Level: The root node is at level 1. If a node is at level 1, then the
children are at L+1. The above diagram shows the levels of all nodes in
that degree.
Height and depth: The height or depth of a degree is defined to the
maximum level of any node in the tree.
Forests: The forest is the set of n>0 disjoint trees (if we remove a root of a
tree, we get forests). In the above diagram, if we remove A, we get forests
with 3 trees.
Binary trees
The binary tree is a finite set of nodes, which is either empty or consists of
a root and two disjoint binary trees called the left sub-tree and right subtree.

In the above example, these three binary trees are different. The second
one has an empty right sub-tree and third one has an empty left sub-tree.
In a binary tree, if all the right sub-trees are NULL then that binary tree is
called skewed to left. Similarly if all the left sub-trees are empty then it is
skewed to right.

Honey Creations

Unit-V-Data Structures
Page 14 of 28

Complete binary tree: A complete binary tree is a binary tree in which


every level, except possibly the last, is completely filled, and all nodes are
as far left as possible.

Full binary tree: a full binary tree of depth K has 2k-1 nodes i.e., the tree
having maximum no of possible nodes.

Linked presentation of binary tree in memory: In linked representation of


binary tree each node will have 3 fields. They are left, data and right as shown
below.

Honey Creations

Unit-V-Data Structures
Page 15 of 28

Traversing Binary Trees: There are 3 standard ways of traversing binary


tree with root R. They are pre-order, in order and post order.
Pre-order traversal:- (root-left-right)
(1)Process the root R
(2) Traverse the left sub-tree of R in pre-order
(3) Traverse the right sub-tree of R in pre-order
Algorithm: PRE ORDER(T)
[T is a binary tree where each node has 3 fields left, data and right. This
algorithm traverses T in pre-order]
Step (1):- if (T!=NULL)
(a) Process (T.data)
(b)Call PRE-ORDER (T.left)
(c) Call PRE-ORDER (T.right)
[end if ]
Step (2):- return
Inorder traversal:- (left-root-right)
(a) Traverse the left sub-tree of R in order.
(b)Process the root R.
(c) Traverses the right sub-tree of R in order.
Algorithm: - inorder (T)
[T is a binary tree where each node has 3 fields: left, data and right. This
algorithm traverses T in inorder]
Step (1):- if(T!=NULL)
(a) Call INORDER (T. left)
(b)Process (T.data)
(c) Call INORDER (T.right)
[end if]
Step (2):- return.
Post-order traversal:- (left-right-root)
(1) Traverse the left sub-tree of R in post order.
(2) Traverse the right sub-tree of R in post order.
(3)Process the root R
Algorithm:- POST OREDR (T)
[ T is a binary tree where each node has 3 fields: left, data and right. This
algorithm traverses t in post order ]
Step (1):- if (T!= NULL)

Honey Creations

Unit-V-Data Structures
Page 16 of 28

(a) Call POSTORDER (T. left)


(b)Call POSTDER (T.right)
(c) Process (T. data)
[ end if ]

Binary Search Tree: Suppose T is a binary tree, and then T is called a binary
search tree (or) binary-sorted tree if each node N of T has the following
properties:

The value of N is greater than every value in the left sub-tree of N

The value of N is equal or less than every value in the right sub-tree of
N.

Hence the inorder of binary tree (T) will give a sorted list.

Inserting a Node Into a Binary Search Tree:A node will always be inserted into its appropriate position in the tree as a leaf.
The following example shows a series of insertions into a binary tree.

Honey Creations

Unit-V-Data Structures
Page 17 of 28

Method: Given the root of binary search tree and a value will be added to the
tree as follows.
(1) Create a new node for a new value and initialize it.
(2) Search for the insertion place in the tree.
(3) Fix pointers to insert the new node.
Algorithm:- INSERT (ROOT, VAL)
[ This algorithm inserts a new node containing the value VAL in the binary
search tree with the ROOT ]
Step (1):- [ create a new node and initialize it]
(a) Get a new node N from avail list.
(b)N. data=val
(c) N. left= NULL
(d)N. right=NULL
Step (2):- [search for the insertion place in the tree]
(a) P=root
(b)Back=NULL
(c) Repeat while (p!=NULL)
(1) Back = p
(2) If ( val < p. data ) then
P=p. data
Else
P=p. right
[ end if]
[end of the step(2) loop]
Step (3):- [ position found, fix pointers to the new node]
[ is the tree empty ]
If ( back==NULL) then
Root=N
Else
If ( val < back. Data ) then
Back. Left = N [insert as left node]
Else
Back. Right = N [ insert as right node]
[ end if ]
[ end if ]
Step (4):- exit
Deleting a Node From a Binary Search Tree:Deleting a node from binary search tree varies from the position of the
node in a tree.
Deleting a leaf node:- (No children)
Setting the appropriate link of its parent to null:-

Honey Creations

Unit-V-Data Structures
Page 18 of 28

Deleting a node with only one child:Make the pointer from the parent to the child of the node c by skipping
the node x.

Deleting a node with two children:Replace the node we wish to delete with the node which is closest value
to the deleted node.

Algorithm:- DELETE(root, val)


[ the node with a value val will be found and deleted from the binary
search tree ROOT is the address of the root, node]
Step (1):- [ search tree for the node containing val ]
P = ROOT [ search pointer ]
Pp = NULL [ parent of p ]
Step (2):- repeat while ( p.data != VAL and p!= NULL)
(a) Pp=P
(b)If ( VAL < P. data then P=P. left)
Else
P. right
[end if]
[ end of step(2) loop ]
Step (3):- if (P=NULL) then
(a) Write ( VAL not found )
(b)Exit
Step (4):- handle the case when p has two children

Honey Creations

Unit-V-Data Structures
Page 19 of 28

(a) [ initialize pointers to find max in the left sub-tree f p]


S=p. left, ps=p
(b)[find the right most node value]
While (s. right != NULL)
(1) Ps=p
(2)S=s. right
[ end of step (a) loop]
(c) [ store a max value in deleted node]
p. data=s. data
(d) [point p to s ]
P=s
Pp=Ps
[ end of step (4) if structure ]
Step (5):- [ p has almost one child and store it in c ]
if (p. left=NULL) then c=p. right
else
c=P.left
[ end if ]
Step (6):- [ delete the node ]
If (P=ROOT) then ROOT = c [ if it is root node ]
Else
(a) [ is p. left (or) right child of Pp]
If (Pp. left = P) then Pp. left =c
Else
Pp. right = c
[ end if]
[ end if ]
Step (7):- [ return the deleted node p to avail list ]
Step (8):- exit

GRAPHS
A graph is a collection of vertices (nodes), which are joined by edges. A
graph G consists of two sets called vertex V and edge E. V is a finite nonempty set of vertex (nodes or points) and E is a finite set of pairs of vertices.
Each pair in E is an edge of G. A graph can be written as G=(V, E).
Any two nodes, which are connected by an edge in a graph, are called
adjacent nodes.
In a graph G=(U,V) and edge which is directed from one node to another
is called a directed edge. An edge which has no specific direction is called an
un-directed edge. A graph in which every edge is undirected is called an
undirected graph and in which every edge is directed is called directed
graph. If some of the edges are directed and some are un-directed in a graph
then that graph is called mixed graph.

Honey Creations

Unit-V-Data Structures
Page 20 of 28

Ex:- In the following diagram the directed edges are known by means of
arrows, which also shows the direction.

In the above diagram (2) and (5) are directed graphs. (3) and (6) are undirected graphs, (4) is a mixed graphs, (1) is either a directed (or) un-directed
graph.
Let V, E be a graph and let XE directed edge associated with ordered
pair nodes then the edge X is said to be initially (or) originating at U and
terminating (or) ending at V. the node U and V are called the initial and
terminal nodes of the edge X.
An edge of a graph which joints a node to itself is called a loop.
Direction of a loop is of no significance. Hence it can be considered either a
directed (or) un-directed edge. If certain pairs of nodes are joined by more
than one edge then such edges are called parallel edges. Any graph which
contains some parallel edges is called a multi-graph. If there is no more than
one edge between pairs of nodes then such a graph is called a simple graph.

A graph in which weights are assigned to every edge is called a weighted


graph.

In a graph a node which is not adjusted adjacent to any another node is called
isolated node. A graph with isolated node is called a null graph i.e. the set of
edges in a null graph is empty.

Honey Creations

Unit-V-Data Structures
Page 21 of 28

In a directed graph, for any node V the no of edges which have V as the
initial node is called the out degree of the node V. The no. of edges which
have V as their terminal node is called the in degree of the node. The sum
of the out degree and in degree of a node V is called its total degree.
Let G=(V,E) be a simple di-graph, consider a sequence of edges of G
such that the terminal node of any edge in the sequence is the initial node of
next edge.
G= ( ( v1,v2), (v2,v3)..(vk-1,vk) ) can be written as
G= ( v1,v2,v3.vk-1,vk).
Path: - A path is said to be traverse through the node appearing in the
sequence, originating in the initial node of the first edge and ending in the
terminal node of the last edge in the sequence. The no of edges appearing in
the sequence of a path is called the length of a path.
Ex:- consider the graph some of the paths originating in the node 2 and ending
in the node 4 are

P1: (2,4)
P2: ((2,3),(3,4))=(2,3,4)
P3: ((2,1),(1,4))=(2,1,4)
P4: ((2,3),(3,1),(1,4))=(2,3,1,4)
P5: ((2,3),(3,2),(2,4))=(2,3,2,4)
P6: ((2,2),(2,4))=(2,2,4)
Representation of a graph: There are two common ways to represent a
graph. They are sequential representation and linked representation. The
sequential form uses a square table i.e., in matrix form.
Sequential Representation of a Graph ( Matrix Representation):Let G=(V,E) be a simple di-matrix in which V={ v1,v2.vn} are the
nodes ordered from v1 to vn.
An nxn matrix A whose element aij is given by,
If G is a di-graph,
Aij= 1, if vi,vj EE=0, otherwise
If G is a undirected graph,
Aij=1, if (vi,vj)EE (or) (vi,vj)EE=0, otherwise.
Then A is called adjacency matrix of the graph G.

Honey Creations

Unit-V-Data Structures
Page 22 of 28

Any element of the adjacency matrix is either 0 or) 1.


Ex:- some graphs and their adjacency matrices are shown below.

Properties:(1) A(, 1<i<n, Vn vertex graph having without loop.


(2)The adjacency matrix of an un-directed graph is symmetric i.e.,
A(I,j)=A(j,i), 1<i<n and 1<j<n.
(3)For an n-vertex undirected graph Eni=1 aij= Enj=1 aji= di for 1<i<n, where
di is the degree of vertex I.
(4)For an n-vertex di-graph Eni=1 aij=di out and Enj=1 aji=di in for 1<i<n then
total diagram =di out+ di in.
(5)In multi-di-graph (or) a weighted graph we write a(I,j)=wij where wij
denotes either the multiplicity (or) the weight of the edges (vi,vj)
If (vi,vj) E then wij=0.
(6)For a null graph which consists of only n nodes but does not contain
edges, the adjacency matrix contains only 3 errors i.e., the adjacency
matrix is null matrix. If there are loops at each node but no other edges
in the graph, then the adjacency matrix is a unique matrix.
Path matrix: let G=(v,b) be a simple graph which contains n nodes that
are assumed to the ordered, and n*n matrix p whose elements are given
by p(i,j)=1, if there exist a path from vi to vj then p is called a path matrix
(or) rehabilitee matrix.
The path matrix only shows the presence (or) absence of at least one
path between a pair of point and also a presence of a cyclic at any node. It
does not show all the paths that may exit.

Graph traversal:- In many applications all the vertices in the graphs are to
be visited. There are two types of graphs traversal methods. They are
1. Breadth first search (BFS)
2. Depth first search (DFS)
Breadth first search (or) breadth first traversal:In BFS we start at vertex and mark it has visited. All the unvisited vertices
adjacent from v are visited next, putting the vertices adjacent to these in a
waiting list to be traversed after all vertices adjacent to V.

Honey Creations

Unit-V-Data Structures
Page 23 of 28

Algorithm:- BFS(V)
[ A BFS of graph is carried out beginning at vertex v. all vertices are marked as
visited (i) =1. The graph G and array visited are global and visited is
initialized to zero. Q is a queue of unexplored vertices]
Step (1):- [initialize first node and mark it as visited]
U=V
Step (2):- [initialize Q to be an empty queue ]
Step (3):- [repeat for even
(a) Repeat for all vertices w adjacent U do.
(1)[ if w is not visited then make it has visited ]
If (visited [w]=0) then
(i.2) visited [u]=1
[ end if ]
[ end if ]
(b)[ all vertices are visited ]
If q is empty then exist.
(c) [ get first un-explored vertex]
Delete Q( )
[ end step (3) loop]
Step (4):- exit
If BFS is used on a connected undirected graph then all vertices in G
get visited and the graph is traversed. If G is not connected, then at least one
vertex of G is not visited. A complete traversal of G can be repeatedly calling
BFS, each time with a new unvisited starting vertex.
Algorithm:- BFT(G,N)
[breadth first traversal of a graph G with N vertices is an array of n elements]
Step(1):- [ may all vertices as unvisited]
VISITED[i]=0
Step(2):- [ repeatedly call BFS for all unvisited vertices]
Repeat for i=1 to n do.
(1)If ( VISITED [i]=0) then call BFS(i)
[ end of step (2) loop]
Step(3):- exit.
Depth first traversal (or) depth first search:In DFS, we start vertex V and mark it as visited let w1,w2..wk be the
vertices adjacent to V. then we shall next visit w1 and keep w2.w3.wk

Honey Creations

Unit-V-Data Structures
Page 24 of 28

waiting. After visiting w1 we traverse all vertices which adjacent to it before


returning to traverse w2, w3, w4.wk.

Algorithm:- [ given an un-directed (or) directed graph G=(V,E) with n vertices


and an array visited (n), initially set to 0. This algorithm visits all these vertices
reachable from V. G and visited are global]
Step(1):- [ mark the vertex as visited ]
VISITED[V]=1
Step(2):- Repeat for each vertex w adjacent from v do
(a) If visited[w]=0 then call DFS(w)
[end of step (2) loop]
Return
If DFS is used on a connected un-directed graph then all vertices in G get
visited and the graph is traversed. If G is not connected, then at least one
vertex of G can be made by repeatedly calling DFS, each time with a new unvisited starting vertex.
Algorithm:- DFT(G,N)
[Breadth first traversal of graph G with N vertices visited is an array of n
elements]
Step (1):- [mark all vertices as un-visited]
Repeat for i=1 to n do
VISITED [i]=0
[end for]
Step (2):- [repeatedly call DFS for all un-visited vertices]
Repeat for i=1 to n do
(1) If (VISITED[I]=0) then call DFS(i)
[end of step(2) loop
Step (3):- exit.
APPLICATION OF DATA STRUCTURE
(a)
Application of stacks
1. Stacks are used in recursion process
2. Stacks are used in conversion of in-fix expression, post-fix expression
(or) pre-fix expression.
3. Stacks are used in evolution of post-fix (or) pre-fix expressions.
4. Stacks are used in 3D-methods (if they are implemented in nonrecursive method)
5. Stacks are used in DFT of a group.
6. Stacks are used in implementing sequence of function call.
(b)
Applications of queues:The following are the important applications of a queue.

Honey Creations

Unit-V-Data Structures
Page 25 of 28

1. Time sharing operating system in which CPU is scheduled for different


jobs.
2. Queue is used in page replacement algorithm of an operating system.
3. Queues are also used in multi-programming operating system (o.s) in
which it is used to hold a set of programmes ready for execution.
Queues are used in BFT of a graph.
(c)
Applications of linked lists:1. Memory management:- linked list are useful in managing memory as
dynamic i.e., DMA.
2. Polynomial manipulations:- the operations on polynomial such as
addition, subtraction, multiplication etc are easily implemented using
linked lists.
3. Insertions and deletions in graphs of data:- the insertions and
deletions are efficiently performed when linked lists are used to
maintain the group of data.
(d)
Applications of trees:1. In computer science, trees are used to organise information in
hierarchal structure in the data base systems.
2. Trees are used to represent the synaptic structure of source program
in compilers.
3. Trees are used in conversions of the in-fix expression to post-fix 9or)
pre-fix expression.
4. Trees are used in o.s level to view the directory list in.
5. Trees are used to analyse networking circuits.
(e)
Applications of graphs:1. Graphs are used in product scheduling with which is a technique
offer known as PERT/CPM (project evolution and review technique/
partial path method.
2. Graphs are used to analyse networking circuits.
3. Graphs are used to find shortest path in order to minimize the
material moments.
4. One of the main applications of graphs is topological sorting.

Graphs
Minimum Spanning Tree:
Minimum spanning tree is related to the weighted graph.
Minimum spanning tree is defined as that the sum of all the weights of
all the edges in the tree is minimum.
There are several methods available for finding minimum
spanning tree of a graph. Out of them, two methods are known to be
efficient.
Kruskals algorithm
Prims algorithm
Kruskals Algorithm:
1. List all the edges of the graph G in the increasing order of weights.

Honey Creations

Unit-V-Data Structures
Page 26 of 28

2. Select the smallest edge from the list and add it into the spanning
tree (initially it is empty) if the inclusion of this edge does not
make a cycle.
3. If the selected edge with smallest weight forms a cycle, remove it
from the list.
4. Repeat steps 2-3 until tree contains n-1 edges of list are empty.
5. If the tree T contains less than n-1 edges and the list is empty.
Spanning tree is possible for the graph else return the minimum
spanning tree T.

SORTINGS:
Sorting means placing the collection of values in one order either
increasing order or decreasing order.
There are different types of sorting, they are:
1. BUBBLE SORT:
Bubble sorting is an algorithm in which we are comparing first
two values and put the larger one at higher index. Then we take next
two values and put these values and place larger vale at higher index.
This process is repeated till the largest value is reached at last index.
Then start again from zero index up to n-1 index. The algorithm follows
the same steps repeatedly till elements are sorted
2. SELECTION SORT:

Honey Creations

Unit-V-Data Structures
Page 27 of 28

In selection sorting algorithm, find the minimum value in the


array then swap it first position. In the next step leave the first value and
find the minimum value within remaining values using same steps.
Working Of Selection Sort:
Say we have an array unsorted a[0], a[1], a[2], . . . ,a[n-1] and a[n]
as input. Then the following steps are followed by selection sort
algorithm to sort the values of an array. Say we have a key index_of_min
that indicate the position of minimum value.
1. Initially variable index_of_min=0.
2. Find the minimum value in the unsorted array.
3. Assign the index of the minimum value into index_of_min variable.
4. Swap minimum value to first position.
5. Sort the remaining values of array (Excluding the first value).
3. INSERTION SORT:
Insertion sorting algorithm is similar to bubble sort. But insertion
sort is more efficient than bubble sort because in insertion sort the
elements comparisons are less as compare to bubble sort.
Insertion sorting takes the element from left, assign that value in
to the variable. Then compare that value with previous values. Put the
value so that values must be lesser the previous values. Then assign the
next value to a variable and follow the same steps relatively till the
comparison reached to end of the array.
4. QUICK SORT:
Quick sort is a comparison sort. The working of quick sort
algorithm depends on the divide and conquers strategy. A divide and
conquers strategy is dividing an array into two sub arrays. Quick sort is
one of the fastest and simplest sorting algorithms.
In quick sort algorithm pick first element from an array of
elements. This element is called as pivot element. Then again start
comparison from left to right with pivot till lesser element is find. If the
index of greater value is minimum then swap the greater and lesser
values otherwise swap the lesser value with pivot element. So that pivot
element is fixed in correct place. From that element left side elements
are one sub problem and right side elements are another sub problem.
So each problem recursively solved using above same quick sort
technique.
TOPOLOGICAL SORTING:
Topological sorting is an ordering of vertices of graph.

A simple algorithm to find a topological ordering is to find without


any vertex within degree is zero. That is a vertex without any
predecessor. We can then add this vertex in an ordering set (initially it is
empty) and remove it along with its edges from the graph. Then we
repeat the same strategy on the remaining graph until is empty.

a) Initial graph: indegree(v2)=0

Honey Creations

Unit-V-Data Structures
Page 28 of 28

b) After adding v2 into the ordering set and removing it from the graph.
next indegree(v5)=0.

c) After adding v5 into the ordering set and removing it from the graph.
next indegree(v7)=0.

d) After adding v7 into the ordering set and removing it from the graph.
next indegree(v4)=0

e) After adding v4 into the ordering set and removing it from graph next
indegree of both v1 and v6 is 0. v1 is selected for next.

f) After adding v1 into the ordering set and removing it from the graph.
next indegree(v6)=0

g) After adding v6 into the ordering set and removing it from the graph.
The graph becomes empty.

h) Topological order is generated.

Honey Creations

You might also like