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

Unit 4. Data Structure-15.9.2022

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

Unit 4. Data Structure-15.9.2022

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

Unit 4.

Data Structure
In the modern world, data and its information have significance, and there are different
implementations taking place to store it in different ways. Data is simply a collection of facts and
figures, or set of values in a particular format that refers to a single set of item values. The data
items are then classified into sub-items, which is the group of items that are not called the simple
primary form of the item.
In the context of computers, the data structure is a specific way of storing and organizing data in
the computer's memory so that these data can be easily retrieved and efficiently used when
needed later. The data can be managed in many different ways, such as a logical or mathematical
model for a particular organization of data is called a data structure.
There are two types of data structure – Linear and Non-linear. In linear data structure the
elements are arranged in the linear order or in a sequence. The examples of the linear data
structure are: Arrays, Queues, Stacks, Linked lists. In non-linear data structure the data is
arranged with hierarchical relationship between different elements. The examples of the non-
linear data structure are: Tree and Graph.
In this unit you will learn all these data structures with their memory representation and
algorithms for traversal, insertion and deletion of elements.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 1 of 41


Chapter 16. Introduction to Data Structure
Everybody of us are having one or other kind of identity card. Let us take an example of a unique
ID Aadhaar card issued by the Government of India. In this card you can easily observe that there
are lot of data items such as Name, Date of Birth (DOB), Gender as Male or Female, your
photograph and Aadhar number which is unique.

Fig. 16.1 Data structures used in Aadhaar card


In real life we always want to deal with different sets of values such as the name of a student or
person. Every person living in India has an Aadhaar number, every city or village in India has a
pin code and also every student will score some marks in examination. Whenever we are dealing
with different situations then we are dealing with the different sets of values.
In this Chapter you will understand the concept of data structure, different types of data
structures and operations performed on data structures.
Data Structure
Data Structure is the specialized means of organizing and storing data in computers to access
the data easily. If the data is stored in organised manner then it is possible to perform operations
on the data more efficiently. There are different ways to organize data and accordingly there are
different types of data structures. Some examples of Data Structures are arrays, Linked List,
Stack, Queue, etc. Data Structures are widely used in almost every aspect of Computer Science
i.e. Operating System, Compiler Design, Artificial intelligence, Graphics and many more. It is the
fundamental and key topic to begin with the software development. The software developers
should have the sound knowledge of data structures. Computer programming languages are used
to implement algorithms on computers.
Data Structures are the main part of many computer science algorithms as they enable the
programmers to handle the data in an efficient way. It plays a vital role in enhancing the
performance of software or a program as the main function of the software is to store and retrieve
the user’s data as fast as possible.
Basic Terminology
It is important to understand the basic terms before knowing to all about the data structures. The
data items are classified into primitive and group data items.
Primitive data item – Data are the elementary value or the collection of values. The data
elements or items that cannot be further divided are called as the primitive data elements. For
example, “Roll Number” of a student is a unique number and it cannot be further divided into
different items.
Group data item – The data elements that can be further divided into data items are called as the
group items. For example, the “Student Name” which can be further divided into three parts such
as, First Name, Middle Name and Last Name, such data items can be called as a group data item.
Attribute and Entity – The data items with some property or attributes is called as “Entity”. This
entity can be assigned numeric or non-numeric value. For example, for the property or attribute
“Age”, you can assign any numeric values such as 17.
The entities with similar attributes are called as entity set. For example, students in a class, or
employees in the organisation.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 2 of 41


Every attribute of entity set has a range of values. For example, range of age can be from 0 to 100.
The data with given attribute is called as information or processed data. The data of the student
such as marks obtained in the subject can be processed to obtain the information in the form of
result as “pass” or “fail”.
Elementary data organization
Data can be organized in linear data structure the elements are into hierarchy of fields, records
and files. The Figure 16.2, shows the file containing three records with each record is having three
fields. Every field has certain data value associated with it. Let us discuss these terms in detail.

Fig. 16.2 Elementary data organization


Field – Field is a single elementary unit of information representing the attribute of an entity.
There can be any number of fields for any single entity. For example, Roll number, Name of
student, and Marks scored by the student are different fields.
Record – Record is a collection of field values. For example, for student entity, Roll Number,
Name and Marks scored are the three different fields. Then the data value for these fields such as
“4301, “Anil”, “71” form one record.
A record may contain many fields but any one field has a unique value that will not be repeated
for other record is called as “Primary Key”. For example, Roll Number of a student cannot be
repeated for other student and hence it is a unique and forms a primary key for this record.
File – A File is a collection of various records of one type of entity. For example, the data of several
students for these three fields form the several records and collection of all the records will form
the file.
A file can have a fixed length records or variable length records. Many times, the length of the
records is fixed but it is also possible to have a variable length record. It is necessary to specify
the minimum and maximum length for each field of the record. For example, we can have 4 digits
for Roll Number, 20 characters for Name and 2 digits for Marks.
Need of Data Structures
Fields, Records and Files are the elementary data organisation techniques. But these techniques
are not sufficient to process all type of data in many applications in real life. Hence, we require
more complex data structure such as arrays, stacks, queues, linked lists, trees, and graphs. As
applications are getting complex and amount of data is increasing day by day, following problems
may arise.
Processor speed – To handle very large amount of data, high speed processing is required, but as
the data is growing day by day to the billions of files per entity, processor may fail to deal with
that much amount of data.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 3 of 41


Data Search – Consider an inventory size of 106 items in a store, if our application needs to
search for a particular item, it needs to traverse 106 items every time, results in slowing down the
search process.
Multiple requests – If thousands of users are searching the data simultaneously on a web server,
then there are the chances that a very large server can be failed during that process
in order to solve the above problems, data structures are used. Data is organized to form a data
structure in such a way that all items are not required to be searched and required data can be
searched instantly.
Advantages of Data Structures
Efficiency – Efficiency of a program depends upon the choice of data structures. For example:
suppose, we have some data and we need to perform the search for a particular record. In that
case, if we organize our data in an array, we will have to search sequentially element by element.
hence, using array may not be very efficient here. There are better data structures which can
make the search process efficient like ordered array, binary search tree or hash tables.
Re-usability – Data structures are reusable, i.e. once we have implemented a particular data
structure, we can use it at any other place. Implementation of data structures can be compiled
into libraries which can be used by different clients.
Abstraction – Data structure is specified by the ADT which provides a level of abstraction. The
client program uses the data structure through interface only, without getting into the
implementation details.
Classification of Data Structure
Data Structures can be classified basically into two categories – primitive and non-primitive data
structure as shown in Figure 16.3. The data structures that cannot be further divided into other
sub-items are called as the primitive data structures or simple data structures or simply data
types. For example, it is not possible to further divide the integer or real number. The primitive
data structures have integer, real, character and Boolean data types. The non-primitive data
structures are categorized in linear and nonlinear data structures.

Fig. 16.3: Categories of data structure – primitive and non-primitive


Linear Data Structures
A data structure is called linear if all of its elements are arranged in the linear order or in a
sequence. In linear data structures, the elements are stored in non-hierarchical way where each
element has the successors and predecessors except the first and last element. For example, the
stacks, queues and linked list are the linear data structure.
Types of Linear Data Structures are given below:

Junior Software Developer, Class XI, Unit 4. Data Structure Page 4 of 41


Arrays – An array is a collection of similar type of data items and each data item is called an
element of the array. The data type of the element may be any valid data type like char, int, float
or double.
The elements of array share the same variable name but each one carries a different index
number known as subscript. The array can be one dimensional, two dimensional or
multidimensional.
The individual elements of the array age are:
age [0], age [1], age [2], age [3], ……… age [98], age [99].
Linked List – Linked list is a linear data structure which is used to maintain a list in the
memory. It can be seen as the collection of nodes stored at non-contiguous memory locations.
Each node of the list contains a pointer to its adjacent node.
Stack – Stack is a linear list in which insertion and deletions are allowed only at one end, called
top. A stack is an abstract data type (ADT), can be implemented in most of the programming
languages. It is named as stack because it behaves like a real-world stack, for example: – piles of
plates or deck of cards etc.
Queue – Queue is a linear list in which elements can be inserted only at one end called rear and
deleted only at the other end called front.
It is an abstract data structure, similar to stack. Queue is opened at both end therefore it follows
First-In-First-Out (FIFO) methodology for storing the data items.
Non-Linear Data Structures
This data structure does not form a sequence i.e. each item or element is connected with two or
more other items in a non-linear arrangement. The data elements are not arranged in sequential
structure. For example, trees and graphs are the nonlinear data structures.
Types of Non-Linear Data Structures are given below:
Trees – Trees are multilevel data structures with a hierarchical relationship among its elements
known as nodes. The bottommost nodes in the hierarchy are called leaf node while the topmost
node is called root node. Each node contains pointers to point adjacent nodes.
Tree data structure is based on the parent-child relationship among the nodes. Each node in the
tree can have more than one child except the leaf nodes. Each node must have parent node except
the root node. Trees can be classified into many categories which will be discussed later in this
unit.
Graphs – Graphs can be defined as the pictorial representation of the set of elements (represented
by vertices) connected by the links known as edges. A graph is different from tree in the sense
that a graph can have cycle while the tree cannot have the one.
Operations on data structure
It is possible to write computer programs to perform any operation on the data structure. For this
it is required to write an algorithm. Algorithm is a set of steps written to perform the operation.
Every algorithm is associated with complexity. The complexity of algorithm refers to the time and
space requirement to execute that algorithm. The most common operations that can be performed
on data structures are as follows.
Traversing – Every data structure contains the set of data elements. Traversing the data
structure means visiting each element of the data structure in order to perform some specific
operation like searching or sorting. For example, if we need to calculate the average of the marks
obtained by a student in 6 different subjects, we need to traverse the complete array of marks and
calculate the total sum, and then we will divide that sum by the number of subjects i.e. 6, in
order to find the average.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 5 of 41


Insertion – Insertion can be defined as the process of adding the elements to the data structure
at any location. If the size of data structure is n then we can only insert n-1 data elements into it.
Deletion – The process of removing an element from the data structure is called Deletion. We can
delete an element from the data structure at any random location. If we try to delete an element
from an empty data structure then underflow occurs.
Searching – The process of finding the location of an element within the data structure is called
Searching. There are two algorithms to perform searching, Linear Search and Binary Search.
These will be discussed later in this unit.
Sorting – The process of arranging the data structure in a specific order is known as Sorting.
There are many algorithms that can be used to perform sorting, for example, insertion sort,
selection sort, bubble sort, etc.
Merging – When two lists List A and List B of size M and N respectively, of similar type of
elements, clubbed or joined to produce the third list, List C of size (M+N), then this process is
called merging.
Summary
 Data structure is a way to organize data in computes so that it can be accessed efficiently.
 Data can be organized into hierarchy of fields, records and files.
 Field represents an attribute of entity.
 Record is a collection of filed values.
 File is a collection of records.
 A file can have a fixed length records or variable length records. The minimum and
maximum length of records can be specified.
 Data structure is classified into primitive and non-primitive data structures.
 Primitive data structure are simple data types such as Integer, Real, Character and
Boolean.
 Arrays, linked list, stacks and queues are the linear data structure as its elements form a
sequence.
 Trees and Graphs are the non-linear data structure as its elements cannot be arranged
sequentially.
 An array is a linear list of elements. It can have one or more dimensions.
 A Linked list is a list in which each element has a link to Next element. Link lists are more
efficient than arrays.
 Stack is a liner list in which insertion and deletion takes place at one end only.
 Queue is a liner list in which insertion takes place at rear end and deletion takes place at
front end.
 In Tree data structure has root and leaves that represents hierarchical relationship
between elements.
 Graph is a pictorial representation of elements along with links. There may not be
hierarchical relationship.
 Operations performed on data structures are: Insertion, Deletion, Traversing, Searching,
Sorting, and Merging.
 Algorithms i.e. set of steps can be written to perform each operation. Complexity of
algorithm refers to time and space required in terms of input size.
CHECK YOUR PROGRESS
A. Multiple choice questions
1. The specialized means of organizing and storing data in computers to access the data
easily are (a) algorithm (b) flowchart (c) data structures (d) data flow diagram
2. The data items with some property or attributes is called as (a) Entity (b) File (c) Field (d)
Record
3. Record is a collection of (a) Entity values (b) Files (c) Field values (d) Bytes

Junior Software Developer, Class XI, Unit 4. Data Structure Page 6 of 41


4. Which of the following is not linear data structure (a) array (b) stack (c) queue (d) tree
5. Which is odd data structure (a) array (b) stack (c) queue (d) tree
B. Fillin the Blanks
1. The data structures that cannot be further divided into other sub-items are called as the
__________ data structures.
2. The entities with similar attributes are called as __________
3. Data structure is called as ________ if its elements can be arranged in a sequence.
4. In ___________ data structure, elements cannot be arranged in sequence.
5. File is a collection of _________________.
C. State whether True or False
1. A file can have a fixed length records or variable length records.
2. In linked list access to data is random.
3. A tree is a hierarchical structure.
4. An array is a non-linear list of elements.
5. A file can have a fixed or variable length records.
D. Short answer questions
1. What is a data structure?
2. What are linear and non-linear data structures?
3. What are the common operations performed on data structures?
4. What do you mean by elementary data organization?
5. Write down various real-world applications where linear data structure is used?

Junior Software Developer, Class XI, Unit 4. Data Structure Page 7 of 41


Chapter 17. Linear Arrays
Suppose you have prepared the list of items to purchase from the shop. If the number of items is
not much more then you just remember it. When you visit the shop you just recall it from your
memory or list prepared on the piece of paper to purchase these items. When you store such
items in computer and retrieve it one by one, the similar process is carried out in the data
structure known as linear array.
In this chapter, you will understand the data structure linear array and different operations that
can be performed on linear arrays with their algorithms.
Array
An array is a linear list of elements where all elements are of similar type. Array can be of one
dimension or more than one dimension. It uses a script variable or index variable to refer to
elements of array. The index of an array always starts with 0 and goes up to N-1 where N is size of
the array. The starting index 0 is called as a lower bound and the highest index N-1 is called as an
upper bound.

Fig. 17.1 Representation of array elements and index


For example, A [3] refers to the 4th element of array A i.e. 98.
A Two-dimensional array has rows and columns. A table of values is a two-dimensional array. It
requires two index variables.
For example, A [2][3] refers to an element from third row and fourth column.
Figure 17.1 shows the array of one dimension. There can be the different elements of the array
and these elements of the array can be stored in successive memory locations. The index variable
or subscript is used to refer the element of array.
The two-dimensional array has rows and columns form a table. Such table values can be stored in
memory by using two-dimensional array. In two-dimensional array there are two indices. For
example, A [2][3] refers to the element of third row and fourth column.

Fig. 17.2 Row and column index in two-dimensional array


Observe the Figure 17.2, the first element is in first tow and first column, hence it has indices
[0,0], second element is in first tow and second column with indices [0,1]. The first index digit is
row index and second index digit is the column index.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 8 of 41


Representing array in memory
The elements of array are stored in successive memory locations as shown in Figure 17.3. For
example, the first element is stored in the memory location starting with address 1001. Suppose
each element requires two memory locations, then the element will be stored in memory location
1001 and 1002 and the Next memory location 1003 will be available for second element. The
value of first element is 20, the value of the second element is 50 and in this way many elements
can be stored in the array.
Memory
Value Index
Address
1001
1002
20 0
1003
1004
50 1
1005
1006
102 2
1007
1008
600 3
1009
1010
2 4
1011
1012
34 5
1013
1014
500 6
1015
1016
100 7
Fig. 17.3 Array representation in memory
The first element memory address is called as a base address. In the above example the base
address of the array is 1001. Suppose LA is the name of the Linear array, then the its base
address can be written as Base (LA). It is possible for computer to calculate the address of any
element of array and for such calculation it is not necessary to visit each and every element of
array. It can be calculated by using the following formula.
LOC (LA[K]) = Base (LA) + W (K – Lower Bound)
Where W is number of words per memory cell, LA is linear array, and Base (LA) is base address of
Linear Array LA.
For example, to find out the address of 4th element,
LOC (LA[4]) = 1001 (LA) + 2(4 - 1)
= 1001 + 6
= 1007
So, the memory address of the fourth elements starts at memory location 1007.
Operations on Array
Arrays are used in many programming situations. The operations that can be performed on arrays
are,
Insertion – Adding new element into structure. In this operation it is possible to add a new
element in the exiting element.
Deletion – Removing element from structure. Here it is possible to delete the existing element
from the array.
Traversing – Accessing each element of structure. It means it is possible to access each element
of the array to perform the required operation on it.
Searching – Finding an element in structure. It is possible to find or search an element in the
array list.
Sorting – Arranging in ascending/descending order. It is possible to sort the array either in
ascending or descending order.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 9 of 41


Merging – Combining two or more elements. This operation allows to combine two or more
elements to form a new array.
In this session the most common operations performed on array such as traversing, insertion and
deletion are discussed.
Traversing Linear Array
Traversing means accessing each element of array exactly once. The algorithm for traversing a
linear array is given below.

Algorithm for traversing of linear array


1. [Initialize counter] Set K: = LB.
2. Repeat Step 3 and 4 while K <= UB.
3. [Visit element] Apply PROCESS to LA[K]
4. [Increment counter] Set K: = K + 1
5. [End of step 2 loop]
6. Exit

In the above algorithm of traversing of array, initially the counter K is set to lower bound means
the lowest value of the index variable. Then the elements of the array are accessed one by one by
incrementing the counter K till the counter has reached to the upper bound. This process will be
repeated till the value of K is less than or equal to upper bound. Thus, it is possible to traverse or
access array elements.
This process can be used for reading or printing the element or making some computation on the
array elements.
The computation of complexity of this algorithm will be of the order n. If there are n elements in
the array then it is necessary to visit each element once. This will increase the complexity of the
order of n.
Insertion
Insertion means adding element into already created array. An element can be easily added at the
end if the memory space is available. To add an element in between the two elements then it is
necessary to create a space between these two elements first. To create a space at particular
position, it is required to shift the rest of elements down. The following algorithm inserts the
element “ITEM” at the Kth position.
Algorithm for insertion of element in a linear array
(Inserting into a Linear Array) INSERT (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K <= N
This algorithm inserts an elements ITEM into the Kth position in LA.
1. [Initialize counter.] Set J: = N.
2. Repeat Steps 3 and 4 white J >= K.
3. [Move Jth element downward] Set LA[J + 1]:= LA[J].
4. [Decrease counter.] Set J: = J – 1.
[End of step 2 loop.]
5. [Insert element.] Set LA[K]: = ITEM.
6. [Reset N] Set N := N + 1.
7. Exit.
In the above algorithm LA is linear array and N is the number of elements in the array, ITEM is
the value of the element of array to be added at the Kth position. So, K should be always less than
or equal to N.
Initially set the counter variable J to N by equation J = N. Then move the J th element to downward
by one position to create the space in that position. This process will be repeated until the counter

Junior Software Developer, Class XI, Unit 4. Data Structure Page 10 of 41


J is greater than or equal to the position K. This can be done by making the use of statement LA
(J + 1) = LA (J) and then decrease the counter J by 1. Then assign the new element ITEM to LA
(K). This will insert the new value ITEM in the K th position. Since a new element is inserted in the
array, set the number of elements from N to N+1.
Deletion
Deletion means removing an element from the existing elements of the array. It is easy to delete
the element at the end of array. To delete an element located in between the two elements then it
is required to move the subsequent element in the side direction so that the vacancy that is being
created can be filled. Algorithm to perform the deletion operation in array is as follows.
Algorithm for deleting an element in array
(Deleting from a Liner Array) DELETE (LA, N, K, ITEM)
Here LA is a liner array with N elements and K is a positive integer such that K <= N
This algorithm deletes the Kth element from LA.
1. Set ITEM: = LA[K].
2. Repeat for J = K to N – 1:
[Move J + 1st element upward.] Set[J]: = LA [J + 1].
[End of loop]
3. [Reset the number N of element in LA] Set N: = N – 1.
4. Exit.
In the above algorithm DELETE the arguments are LA the linear array, N is the number of
number of elements in the array, K is the position of the element to be deleted and ITEM is the
value of the element to be deleted.
Initially set the ITEM to K th position. Now move the element of J+1 position. This process is
repeated for J = K to N – 1. This will move the J+1 st element upward. This is done by using the
statement LA(J) = LA (J+1). Then reset the number of elements of linear array from N to N – 1 as
one element is deleted from the array and therefore it is necessary to reduce the number of
elements from the array by one.
Searching in array
Searching is a process of finding an element in array. In many applications, it is required to find
whether the element is present in the list or not. The searching algorithm is required in such
cases. Complexity of search algorithm is measured in terms of number of comparisons be to made
to find the element. Searching operation need to be performed several times in computer
programming.
There are two types of searching – Linear search and Binary search.
Linear search
It is the simplest type of search operation. In this technique the search element is compared with
each element of array until that element found in the list. If all the elements are compared and
the search element is not found in the list then it is declared that the element is not present in the
array. Linear search is also called as sequential search, because in this technique the search
element is sequentially compared with the first, second up to last element in the list. For example,
consider an array of characters A, B, S, O, L, U, T, E as shown in Figure 17.4 and we want to find
whether the element “U” is stored in the array or not.

Fig. 17.4 Graphic view of Linear search

Junior Software Developer, Class XI, Unit 4. Data Structure Page 11 of 41


It is possible to find out the search element using linear searching. For this first the search
element is compared with the first element. If it is not matched with the search element then it
will be compared with the second element, then third element. This will be continued until the
search element is matched with the element in the array. When the element is found in the list
the search process will stop with the result that the element found in the particular location. But
if the element is not found after comparing all the elements then the result is declared that the
search element is not present in the list. Algorithm for this type of searching using linear search
techniques is given below.
Algorithm for searching using linear search
Linear Search (Array A, Value x)
Step 1: Set i to 1
Step 2: if I > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
The algorithm “Linear Search” with arguments as Array A and Value x. In this algorithm initially,
the control variable “i” is set to 1 and then check the value of I with the number of elements N in
the array. If value of “i” is greater than the number of elements N in the array, then the search
ends with the message that element not found in the list. In the third step the given value of
search element x is compared with the first element in the array. If the value matches, then it will
print the message that the search element is found in the particular location “i” of array. But if
the value does not match then the control variable “i” will be incremented by 1 and again the
process to find the search element will be repeated with the second element and so on until it will
find the match with the search element or the control reaches to the last element of array. This
algorithm is a simple algorithm. The search element will probably be found in the array by
comparing all the elements or in worst case the element may not found in the array and thus the
complexity of the algorithm can be of the order of n, i.e. O(n) as there are n elements in the array
then it requires to check all the n elements if the search element is not found in the list.
Binary Search
It is the most popular type of search operation. In binary search method, the given array should
be sorted array. In Binary Search, a sorted array is repeatedly dividing the search interval in half
and if the value of the search key is less than the item in the middle of the interval, the interval
narrow down the interval to the lower half. Otherwise, the upper half interval will be considered
for searching the element. This process is performed repeatedly until the value is found or the
interval reached to empty. For example, consider a sorted array with the elements as 1,2,3,4,5,6,7
as shown in Figure 17.5.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 12 of 41


Fig. 17.5 Graphic view of Binary search
Suppose the search key is 5. Now in this array the start element is 1 and end element is 7. Hence
the middle element will be 4th element. Then the value of the middle element is compared with the
search key. It is found that the search key is greater than the middle element. Hence it is clear
that the search element will be in the upper half part of the array. The upper part of the array
consists of three elements, where the start element is 5, end element is 7 and middle element is 6.
Then again, the search key “5” is compared with the middle element which is “6”. Now the search
key is less than the middle element, hence the lower part of the search interval will be considered
only to search the search element. The lower part of the array contains only one element i.e. 5.
Hence the search key will be compared with the element of the lower part i.e. “5”. Now at this
stage the match is found with the search element. Hence the result is declared that search
element found in the array. This completes the successful searching of the search element. In this
method, it is observed that the numbers of comparison are quite less than the earlier method and
hence it is much faster than the “Linear Search”. Therefore the complexity of the algorithm is very
low of the order of log n i.e. O(log n). If the array is very short i.e. the numbers of elements are
very less in the array then only it is not possible to get the advantage of binary search method.
But if the list is very large then this method is much faster than Linear Search method. Algorithm
for binary search can be written in number of ways. One of the popular ways to write the
algorithm for binary search is iterative method as follows.
Algorithm for Binary Search
First = 1
Last = N
Middle = < First + Last > / 2
While < First < = Last >
<
If < Array [Middle] < Key >
First = Middle + 1
Else If < Array [Middle] = = Key >
<
Print “Key Found at Location”
Break
>
Else
Last = Middle – 1
Middle = < First + Last > / 2
>
If < First > Last >
Print “Not Found”
Return
In this algorithm the first element is assigned the value 1 and last element is assigned the value
N. The middle element is computed by using the formula (first + last)/2. So initially all these three
variables first, last and middle are computed. Then in loop will be executed till the first element is
less than or equal to last. In the loop the array of middle is checked with the key. If it is less than
the key then assigns the First to Middle + 1. Else if Array of Middle is equal to key then it displays
that “Element found in that location”. Else the Last is assigned to Middle – 1.
If it is equal to key value then it is found that search of key element is successful and element is
found at the particular location.
Summary
 Array is a linear data structure where all elements are of similar type can be accommodate
only.
 Array uses a script variable or index variable to access elements which starts with 0 and
goes up to N-1 where N is size of the array.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 13 of 41


 A Two-dimensional array could have rows and columns.
 Any array elements are stored in successive memory locations.
 It is possible for computer to calculate the address of any element by using the following
formula. LOC (LA[K]) = Base (LA) + W (K – Lower Bound)
 Various operation that could be performed of array data structure are Insertion, Deletion,
Traversing, Searching, Sorting and Merging
 Traversing operation means accessing each element of array exactly once.
 Insertion operation means adding new element into already created array.
 Deletion operation means removing an element from the existing elements of the array.
 Searching operation is a process of finding an element in array.
 Searching operation can be done in two ways i.e. Linear search or Binary search.
CHECK YOUR PROGRESS
A. Multiple choice questions
1. An Array is (a) linear (b) non-linear (c) circular (d) volatile
2. The element of third row and fourth column is referred as (a) A [3][2] (b) A [3][3] (c) A [2][2]
(d) A [2][3]
3. Accessing each element of structure is called (a) insertion (b) deletion (c) traversing (d)
merging
4. Operation to combine two or more elements to form a new array is known as (a) insertion
(b) deletion (c) traversing (d) merging
5. The first element memory address is called as a (a) first address (b) base address (c) high
address (d) low address
B. Fill in the blanks
1. Array uses __________ variable to refer its elements.
2. Arranging data in ascending/descending order is called __________.
3. The complexity of traversing algorithm for an array will be of the order ___
4. In binary search method, the given array should be _______ array.
5. The complexity of the binary search algorithm is ________.
C. State whether True or False
1. An element can be easily added at the end of array if the memory space is available.
2. Searching is a process of finding an element in array.
3. Binary search is also called as sequential search.
4. If the list is very large, then binary search is much faster than Linear Search.
5. Complexity of Linear search is O(n2).
D. Short answer questions
1. What is array?
2. Write algorithm for insertion in an array.
3. How to delete an element located in between two elements of an array.
4. What is Linear search?
5. Write algorithm for Binary search.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 14 of 41


Chapter 18. Stack
Many times, it is observed that books are kept on table one after another. In the same way, the
plates are also placed on one another. This type of arrangement of placing of items on one another
is known as stack. It seems quite interesting that most of the concepts of computer are actually
brought from the real-life situations. The concept of stack data structure is also taken from the
real-life example of stack of books or plates.

Fig.18.1 Stack of books


In this chapter, you will understand the data structure stack, its representation in memory and
the different operations performed on stack.
Stack
A linear list that allows to insert and delete the element from one end only is called as stack. In
the example of books arranged one after another in stack, a book can be removed from topmost
book or any new book can be placed on the top of the stack of book. A stack is a container where
first inserted element goes to the bottom. Stack has a pointer known as stack pointer or top
pointing to the topmost element of the stack.
Stack is called as a Last In First Out (LIFO) as the elements that are inserted in the end will be
removed first from such list. In stack, the topmost element which is inserted last is processed first
and first inserted element is processed in the last. Stack is just like a container where the first
inserted element will go to the bottom as shown in the Figure 18.2. Inserting the first book will go
to the bottom and the second book will come on the top. Inserting the third book will bring that
book on the top. Inserting an element into the stack called as a PUSH and removing an element
from the stack is called as POP. A pointer keeps track of top element of stack.

Fig. 18.2 Stack data structure


Applications of stack
Stack is very useful data structure in implementation of programs for many real-life applications
using recursive functions, evaluations of arithmetic expressions and to solve the problems that
make use of backtracking.
Representation of stack in memory

Junior Software Developer, Class XI, Unit 4. Data Structure Page 15 of 41


The stack data structure is mostly not inherently supported by the programming languages. It
can be implemented using array or linked list. It is possible to access stack and elements through
index variable of array. The value of the index variable can be assigned to the stack pointer or
TOP. In Figure 18.3, an array represents the stack because insertion and deletion can be done at
one end only TOP.

Fig. 18.3 Implementation of Stack using Array


To insert element in the stack, first it is required to increase the TOP pointer by 1 and to delete an
element from the stack, decrease the TOP pointer by 1. Array restricts to create a stack of fixed
size only. On the other hand, if the size of the stack is not known then the linked list is used to
create the stack instead of array.
Creation of stack using array
A stack can be created using one dimensional array of specific size. The data items are inserted or
deleted by using LIFO principle. A variable called TOP is used to insert or delete the element in
stack. Initially the value of TOP is -1. It is incremented by 1 while inserting the element in the
stack and decremented by 1 while deleting the element from the stack.
Operations on stack
Now let’s understand some important operations that can be performed on the stack.
Push Operation
To insert or add a new data element into stack is called as push operation. Now in order to
achieve this push operation, perform the following steps.
Algorithm : Push operation on stack
1. Check if stack if full. If yes then output an error and exit
2. If not, increment top to point to Next empty space
3. Add data element to the stack location pointed by top
4. Return success
First check whether there is space available for the new element. Check if the stack is full or not.
If the stack is full, it is not possible to insert the element. It will output an error. If the Stack is
not full then it is possible to insert the new element into the stack. In such a case, increment the
TOP by one to point to the next empty space. Then add the data element to the stack location that
is being pointed by the top pointer or stack pointer and ultimately will return the success.
Let us take an example of a empty stack as shown in Figure 18.6. The stack is initially empty with
TOP equal to –1. To add the new element in the stack, first increase the TOP by 1. Now value of
TOP becomes 0. Then insert (PUSH) the first element “A”. To add the second element, again
increase the TOP by 1. Now value of TOP becomes 1. Then insert (PUSH) the first element “B”. To
add the third element, increase the TOP by 1. Now value of TOP becomes 2. Then insert (PUSH)
the first element “C”. In this way by using PUSH operation, new elements can be added in the
stack until it becomes full.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 16 of 41


Fig. 18.5 Insertion (Push) operation on stack
Pop Operation
Deletion of an element from the stack is called as POP operation. The steps to perform for POP
operation are given in the following algorithm.
Algorithm : Pop operation on stack
1. Check if stack is empty. If yes, then output an error and exit
2. If not, access data element at which top is pointing.
3. Decrease the value of Top by 1.
4. Return success
First, check the stack is empty or not. In empty stack it is not possible to perform the POP
operation and hence it will give “Underflow Error”. If the stack is not empty then, decrease the
value of the TOP by 1, then POP is successful.
Let us take an example of a stack consisting of the elements A, B, C, D and E, where E is the TOP
as shown in Figure 18.6.

Fig. 18.6 Deletion (Pop) operation on stack


To remove element from the stack, decrease the TOP pointer by 1. Now, it will point to D. In this
way, D will be removed from stack. Space used by E can be made free. POP is successful.
Traversal Operation
Traversal operation visits the each element of stack at least once. The following are the steps to
traverse/display the elements of a stack.
Algorithm : Traversal operation on Stack
1. Check whether stack is Empty or not.
2. If it is empty, then display "Stack is Empty!" and exit.
3. If it is Not Empty, then assign value of Top in var x.
4. Now Access data element at which x is pointing
5. Decrease the value of x by 1 until it becomes 0 (zero).
6. Return success
First, check the stack is empty or not. In empty stack it is not possible to display the items of
hence it will give “Underflow Error”. If the stack is not empty then, copy the value of Top is one
another X variable and display the value of stack at X. Decrease the value of X by 1 until it
becomes -1 and display contents.
Summary

Junior Software Developer, Class XI, Unit 4. Data Structure Page 17 of 41


 Stack is Last in First out (LIFO) list. Element inserted in end will be taken out first.
 In stack, insertion and deletion takes place at one end only.
 In stack insertion of element is called as Push and deletion of element is called as Pop
operation.
 To insert element in stack, Top is incremented by one.
 To delete element from stack, Top is decremented by one.
 A pointer Top keep track of top element of stack.
 Stack is used in many applications such as Recursion, keeping track of function calls,
evaluation of expression, servicing hardware interrupts and solving problems using
backtracking.
 Stack can be implemented by using Array or Linked Lists.
 By using array, a stack of fixed size can be created.
 By using linked list, a stack of any size can be created.
CHECK YOUR PROGRESS
A. Multiple choice questions
1. Stack pointer point to the _________ element of the stack (a) first (b) last (c) topmost (d)
bottom
2. In programming, stack can be implemented using (a) array (b) queue (c) list (d) array or
linked list.
3. In stack, insertion and deletion take place only at (a) front end (b) rear end (c) one end (d)
both end
4. Stack follows (a) LIFO (b) FIFO (c) LILO (d) LOLI
5. Removing an element from the stack is called as (a) Push (b) Pop (c) Delete (d) Remove
B. Fill in the blanks
1. The pointer pointing to the topmost element of the stack is called __________.
2. Stack of variable size can be created using _________.
3. In a stack, element that is inserted in end will be taken out __________.
4. When we delete element from a stack, Top is __________ by one.
5. By using array, we can create a stack of __________ size.
C. State whether True or False
1. In stack, first inserted element is processed in the last (T)
2. Array is used to create a stack of fixed size only. (T)
3. Push operation cannot be performed on empty stack. (F)
4. Pop operation on an empty stack will lead to overflow error. (F)
5. Stack is used in execution of recursive functions. (T)
D. Short answer questions
1. What do you mean by stack?
2. Write algorithm to perform Push operation in stack.
3. State the pop operation in stack with an example.
4. How stack is represented in memory?
5. Why stack is called LIFO based structure?

Junior Software Developer, Class XI, Unit 4. Data Structure Page 18 of 41


Chapter 19. Queue
Whenever there are number of persons approaching for the same task such as purchasing a ticket
in the ticket counter of bus, train or theater, they form a queue to process the task one by one. A
person who enters into the queue first will get ticket first and the person who enters in the queue
at the last will get the ticket at the last. In many places a queue is observed in our daily lives.

Fig. 19.1 : Example of queue


In this chapter, you will understand the basic concept of queue data structure, how it is
represented or implemented in memory and the operations performed on queue.
Queue

Queue is linear data structure in which insertion of the elements takes place at one end and
deletion takes place at another end. The new element is inserted in the rear end or back end and
deletion of the element takes place from the front end. So this data structure is called as a First In
First Out list (FIFO). In this data structure the element that is inserted first will be deleted first,
just as the person who enters in the queue first can exit first.
Fig. 19.2 Operations on Queue
There are two common operations performed on queue that are insertion and deletion, also called
as Enqueue and Dequeue.
Enqueue – Whenever an insertion of element is performed at rear end, then this operation is
called as Enqueue.
Dequeue – Whenever a deletion of element is performed from front end, then this operation is
called as Dequeue.
Queue is a very useful data structure used to store data values temporary in the memory. Queue
is used to write algorithms or programs to achieve sharing of the resources . For example, in the
laboratory of school there is one printer shared among the number of students. Then such printer
sharing is achieved by using the queue data structure.
Representation of queue using array
A queue can be represented by using linear array. There are two variables – Front and Rear that
are used for insertions and deletions operations. Initially the value of front is -1 which indicates
the queue is empty. Consider an array of five elements with values E, M, E, R, G, E as shown in
Figure 19.4. The Front has initial value 0, which will point to the element E. The Rear has value 5
that will point to the last character E.
Insertion of an element in the

Junior Software Developer, Class XI, Unit 4. Data Structure Page 19 of 41


Fig. 19.3 Representation of queue using array
Insertion operation
Initially if the queue is empty and the first element is to be inserted in the queue then set the
value of front and rear to 0 and insert the element at the rear end. To insert the new elements,
keep on increasing the value of Rear by one and insert each element one by one with Rear as
index. The insertion in the queue is possible until the queue becomes full. To check whether the
queue is already full or not, the Rear is compared with MAX – 1 where MAX being the size of the
queue. If queue is full, then return an error “Overflow”.
The algorithm for performing the insertion operation in the queue is as follows.
Algorithm: To insert an element in the queue
Step 1: If Rear = Max - 1
Print “Overflow”
Go to Step 4
[End of If]
Step 2: If Front = -1 And Rear = -1
Set Front = Rear = 0
Else
Set Rear = Rear + 1
[End of If]
Step 3: Set Queue [Rear] = Num
Step 4: Exit
Consider the above queue as shown in Figure 19.3. Now to insert the new element “D” in the
queue, increase the Rear variable by 1 so that it becomes 6. Now insert the new element “D” in the
queue, as shown in Figure 19.4.

Fig. 19.4 Queue after inserting new element


Deletion operation on queue
It is also possible to perform deletion operation on queue. To perform deletion operation first it is
required to check whether the queue is empty or not.
If, the value of front is -1 or value of front is greater than rear, then the queue is empty. Print the
message “Underflow” and exit. Otherwise, keep increasing the value of front by 1 and return the
element stored at the front end of the queue at each time.
The algorithm for performing the deletion operation in the queue is as follows.
Algorithm: To delete an element from the
queue
Step 1: If Front = -1 or Front > Rear

Junior Software Developer, Class XI, Unit 4. Data Structure Page 20 of 41


Print “Underflow”
Else
Set Val = Queue [Front]
Set Front = Front + 1
[End of If]
Step 2: Exit
Consider the above queue as shown in Figure 19.4. To delete the element from the queue remove
the first element and increase the Front variable by 1 so that it becomes 1. Observe that first
element E gets deleted as shown in Figure 19.5.

Fig. 19.5 Deletion operation on queue


D Queue and Priority Queue
D Queue in short called as Deck is a double ended queue in which it is possible to insert the
element from both the ends either from the frontend or from the backend of the queue as shown
in Figure 19.6. It is also possible to remove the element either from the frontend or from the
backend of the queue. So D Queue is a linear list in which elements can be added or removed at
both the ends, but it is not possible to add or remove the elements from the middle of the queue.
This is a hybrid data structure that provides all capabilities of stack and Queue. Deck can be
implemented by the doubly linked list or array. In D Queue the traversing of the element is much
faster than that of the Queue. The time required in searching of the elements is much less in
Deck than a normal queue. It is also possible to have the different versions of the D Queue such
as input restricted deck or output restricted deck. In the input restricted deck insertion is allowed
at one end and deletion is allowed at both ends. In the output restricted deck deletion is allowed
at one end and insertion is allowed at both ends. These are the two forms of double ended queue.

Fig. 19.6 D Queue


Priority Queue
The advantages of the double ended queue are that it can be used for the creation of priority
queue. As you know that queue is FIFO list and whenever we have a queue and where there are
some important jobs in queue and such job requires to wait until their turn comes in. To solve
this problem, it is possible to assign the priority to each element. The element with the highest
priority will be processed with the elements with the lowest priority. In this type of queue, the
priority of the element of the queue will be taken into the consideration. The elements having the
higher priority will be processed first and the element with the lower priority will be processed
later. If there are two elements of the same priority than any suitable method can be used to
process the element. You can make use of FIFO or process the element depending upon the value

Junior Software Developer, Class XI, Unit 4. Data Structure Page 21 of 41


of the element. In time sharing system we can make use of this queue where programs with high
priority will be processed first. It is possible to perform insertion and deletion operation on the
priority queue.

Fig. 19.7 Priority queue – insertion


As shown in the Figure 19.7, every element in the priority queue will be assigned with the priority
level. The elements of queue are arranged in such as way that the elements with higher priority
will go at the Front end and the element with the lower priority will go to the Rear end. The double
ended queue can be used to implement the priority queue. Items in the priority queue are ordered
by some key called as priority index. Items with the highest priority will be kept in the Front end
and the items of the lowest priority are kept in the Rear end for easy access to these elements.
Summary
 Queue is linear data structure in which insertion takes place at one end and deletion takes
place at another end.
 A New element is inserted at Rear End (Back End) and existing element is deleted from
Front End.
 Queue is also called as first in first out (FIFO) list.
 Two most important operations performed on queue are insertion and deletion.
 Queue can be represented by a linked list or an array.
 The start pointer of linked list is used as Front and Rear will store the address of last
element in queue.
 If Front and Rear are equal to NULL then the queue is empty.
 For deletion front is increased by one and for insertion, rear is increased by one.
CHECK YOUR PROGRESS
A. Multiple choice questions
1. A linear list that allows insertion of the elements at one end and deletion at another end is
called (a) Stack (b) Queue (c) Tree (d) Graph
2. Queue follows (a) LIFO (b) FIFO (c) FILO (d) LOLI
3. Insertion of an item in a Queue is called (a) Push (b) Pop (c) Enqueue (d) Dequeue
4. Insertion of element in a Queue is performed at (a) rear (b) front (c) top (d) bottom
5. Removing an element from the queue is called (a) Push (b) Pop (c) Enqueue (d) Dequeue
B. Fill in the blanks
1. If Front and Rear are equal to NULL then the queue is __________.
2. For insertion in a Queue, rear is increased by __________
3. When we delete element from a Queue, Front is __________ by one.
4. By using array, we can create a Queue of __________ size.
5. Queue can be implemented by the __________ list.
C. State whether True or False

Junior Software Developer, Class XI, Unit 4. Data Structure Page 22 of 41


1. In D Queue, the traversing of the element is much faster than that of the Queue.
2. The elements having the higher priority will be processed last.
3. In Priority queue, items of lowest priority are kept in the Rear end for easy access.
4. The double ended queue can be used to implement the priority queue.
5. Queue is used in process scheduling by CPU.
D. Short Answer Questions:
1. What do you mean by Queue?
2. Write algorithm to perform insertion operation in Queue.
3. State the deletion operation in Queue with an example.
4. What is D Queue?
5. Discuss the significance of Priority Queue?

Junior Software Developer, Class XI, Unit 4. Data Structure Page 23 of 41


Chapter 20. Linked Lists
Suppose you entered in your class and you want to find a seat for sitting. In the class few seats
are vacant in different locations. You cannot find a consecutive location to sit adjacent to your
friend. To pass on your copy to your friend you need to know the chain of your few friends
through which you can pass your copy to your concerned friend. This could be achieved by
passing your copy to the next friend starting from you.

Fig. 20.1 Example of linked list


See how the chain of friends pointing to next friend becomes useful to transfer your copy to your
concerned friend. This situation of can be assumed as a linked list data structure in computer
terminology. You can think of classroom as a memory, the virtual address space as the seats, and
any particular memory address as a seat number.
You see, arrays are suitable when we need fast access. Like who's seating at seat number 13 can
be answered in constant time. But arrays require you to declare a fixed size at the compile-time,
due to which memory can be either wasted or fell short.
In this chapter, we will discuss about linked list, the different types of linked list, how the linked
list are represented in memory and also the traversing operation on the linked list. Whereas
linked list is suitable when we need to modify existing data by insertion and deletion because it
doesn't have a fixed size. So, our memory consumption is determined at run time as the linked
list shrinks and grows dynamically in constant time.
Linked list
Linked list is a linear collection of the data elements, which are not stored in the successive
memory location. So, it is possible to store these elements in different parts of the memory even
though they are the part of the same list.

Fig. 20.2 Linked list


Every data element in the linked list will consist of a node and the node will have two parts. The
first part is called as a data and other part is called as a pointer that points to the next element.
This list is called as linked list because there is a linking between the different elements of the list.
So linked list is a collection of nodes where every node will consist of a data and a pointer to the
Next element.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 24 of 41


The first element is called as a Head and the last element is called as a Tail. Head point to the
first element of the linked list and Tail point to the last element. Since Tail is the last element
whose pointer will not point to the Next element. Hence the pointer to Tail is always NULL.
Accessing the elements of linked list is much easier than that the arrays. In arrays, the computer
needs to compute the location of each and every element but in case of linked list the node itself
contains the address of the Next element. Therefore, making access to the elements of the linked
list is quite easy and faster.
The memory requirement for the linked list is comparatively larger than that of array. In case of
array only one form of memory location is required where the data values are stored. But in case
of linked list two arrays (columns) are required. One column to represent the value of the element
and the other column will represent the linked values or memory address values. Thus, the
memory requirement of linked list is larger than that of array.
Linked list is the dynamic data structure. It is possible to increase the number of elements of the
link list even during the program execution, which is not possible in case of array.
Types of linked list
There are different types of linked list as follows:
Singly Linked List – This is a basic linked list in which each node contains data and pointer to
Next element. Last element pointer has NULL value as shown in Figure 20.3. In this type of linked
list, traversing of the elements is possible only in forward direction only.

Fig. 20.3 Singly linked list


In this list the first element has the value “A” and “Next” is the pointer to the Next element B. The
second element is B and “Next” is the pointer to C. In this way the final element will have a value
D and its pointer will have a “NULL” value since there are no further elements in the list. It
indicates that D is a final element of the linked list. This is the simplest type of list.
Doubly Linked list – In this type of linked list each node contains two pointers instead of one
pointer. The first pointer is left pointer “Prev” and second pointer is right pointer “Next”. Figure
20.4 shows the two pointers to the first node i.e. left pointer is “NULL” and right pointer in “Next”.
It is possible to traverse this list in both forward and backward direction.

Fig. 20.4 Doubly linked list


Similarly, the next element D will have the left pointer “Prev” and right pointer “Next”. The
traversing of this list is possible in forward as well reverse direction, i.e. we can visit each element
of the list from both sides. In such list it is possible that leftmost element pointer “Prev” will have
a “NULL” value or the rightmost element pointer “Next” will have a “NULL” value.
Circular Linked List – This is a singly linked list where last node points to first node. Figure 20.6
shows that the last node T is having the pointer “Next” that will point to the first element “L”. This
forms a circular approach hence it is called as circular linked list.

Fig. 20.5 Circular linked list


Representation of linked list in the memory

Junior Software Developer, Class XI, Unit 4. Data Structure Page 25 of 41


The advantage with the linked list is that it is not necessary to represent all the elements in the
memory in successive memory location. They can be stored in any available free memory
locations.
Each element of the link list requires two locations as data value and pointer value. So, to
represent the link list in memory, two array (columns) are required. The first array “ Data” is used
to hold the data values and the second array “Next” is used to hold the pointer or memory address
of the Next element.
For example, consider a linked list as shown in Figure 20.6. The linked list starts with the head
node pointing to the first node. The first node with element “13” has a pointer pointing to the next
node with element “15”. In the same way last node with element “127” has the NULL value as
terminating node.

Fig. 20.6 Representation of linked list in the memory


The second node has value 15 and pointer value is 3045 which points to the third node. The third
node has value 19 and pointer value is 4025, which points to the last element. The last element
has value 27 and pointer value is NULL and hence it will not point to any node further. This
linked list is represented in the memory as shown in the Figure 20.8.

Fig. 20.7 Memory representation of link list


Operations performed on the linked list
There are various operations that can be performed on the linked list.
 Traversing – visiting each element of the list.
 Insertion – inserting a new element in the list.
 Deletion – removing an element from the list.
 Searching – finding an element in the list. Whether the element is present in the list, can
be determined by this operation.
Traversing a linked list
Traversing means accessing or visiting of each and every element of linked list at least once. Now
suppose we have a start pointer or the head pointer which will point to the first element. Suppose
we have an array called Info which contains the values and the array Next which will point to the
Next element. Then it is possible to write the algorithm as given below to perform traversing
operation for the linked list.
Algorithm : Traversing operation on linked list
1. if start = NULL
Print “List is empty”

Junior Software Developer, Class XI, Unit 4. Data Structure Page 26 of 41


Exit
2. Set Next = start
3. Repeat steps 4 and 5 until Next != NULL
4. Access and appl Next → info
5. set Next = Next → Next
End repeat
6. Exit
In the above algorithm, if the start pointer is equal to NULL means the list is empty. Therefore,
exit the algorithm. Otherwise set the pointer to “start” and repeat the Next two steps until the
pointer value is not equal to NULL. Thus, each and every element of “info” can be accessed by
using Next pointer. Then set the pointer to the Next and end the loop. In this algorithm it is
observed that each and every element of the linked list is accessed or visited at least once.
Insertion in the linked list
Adding a new element in the linked list is called as insertion. Insertion of the element in the
linked list can be done either at the beginning or at the end or at specific location of the linked
list. To insert an element in linked list at any location, it is essential to create a new node. This
new node can be inserted at the beginning or at the end or at the specific location of linked list.
The algorithm is discussed below.
a. Insertion at the beginning of the linked list
Consider a linked list as shown in Figure 20.10 with three nodes having the values 5, 10 and 15.
The pointer of the first node 5 will point to the second element, the pointer of the second element
10 will point to the third element and pointer of the third element 15 have a NULL value as it is
the last element of linked list.

Fig. 20.8 Insertion at the beginning of the linked list


The head or start pointer points to the first element of the linked list. To insert a new element at
the beginning of the linked list, the pointer of the new node should point to the element of the first
node, so that the start pointer will point to the new node. The pointer of newly created node will
point to the element of the first node i.e. 5, as shown in Figure above 20.10.
The algorithm to perform the insertion at the beginning of the linked list is given below.
Algorithm: Insert the node at the beginning of the linked list
Step 1: If Ptr = NULL
Print “Overflow”
Go To Step 7
[End of If]
Step 2: Set New_Node = Ptr
Step 3: Set Ptr = Ptr → Next
Step 4: Set New_Node → Data = Val
Step 5: Set New_Node → Next = Head
Step 6: Set Head = New_Node
Step 7: Exit
As per the above algorithm, first check the memory space is available for a New node or not. If
memory space is not available then print message “Overflow”. Once the memory space is allocated

Junior Software Developer, Class XI, Unit 4. Data Structure Page 27 of 41


to the New node, assign the head pointer to the new New node. Then assign the new node pointer
to the first node of the linked list.
b. Insert the node at the end of the linked list
It is also possible to insert the node at the end of the linked list. To insert a node at the end of the
linked list, consider a linked list consisting of three elements as shown in Figure 20.11. To insert
node at the end of the list, it is required to break the link so that the last node should not have a
pointer value equal to NULL. Instead this pointer value should be set to the New node. Allocate
memory for the New node and assign the pointer value of the last node. For this perform the
traversing operation through the linked list. To end up the list assign the pointer value of the New
node to a NULL.

Fig. 20.9 Insertion at the end of the linked list


The steps of algorithm to insert an element at the end of the linked list is given below.
Algorithm : Insert node at the end of the linked list
Step 1: If Ptr = NULL
Print “Overflow”
Go To Step 1
[End of If]
Step 2: Set New_Node = Ptr
Step 3: Set Ptr = Ptr - > Next
Step 4: Set New_Node - > Data = Val
Step 5: Set New_Node - > Next = NULL
Step 6: Set Ptr = Head
Step 7: Repeat Step 8 While Ptr - > Next != NULL
Step 8: Set Ptr = Ptr - > Next
[End of Loop]
Step 9: Set Ptr - > Next = New_Node
Step 10: Exit
In the above algorithm, first step is to check whether there is a free space to create a New node. If
no free space is available then print the message, “Overflow” and exit the program. If it is possible
to create a New node then allocate the memory space to the New node. Then set the Data value
for New node by assigning Info to Data and Next to NULL. The new node is the last element of the
linked list and therefore it is necessary to set the pointer value of the New node to NULL. Then
traverse the list to check if the lists consisting of an element or not. If the list is empty then this
will be the first element. Otherwise traverse through the list by making the use of Repeat – While
loop. Then at the end of the loop set the Next pointer to New. This pointer which is the last
element of the linked list has to be set to the New node.
c. Insert an element into the linked list at a specific location
It is possible to insert an element at the specific location of the linked list. Consider a linked list
whose Start or Head point to the first element as shown in Figure 20.12. It will consist of Data
and the Next pointer. To insert a new element after the second element, it is required to break this
link and create some New node. Then assign the pointer value of the second element to the Data
value of the New node and then the set the pointer value of the New node to the Data value of the
Next node. Thus, the New element get inserted after the second element in the linked list as third
element and Previous third element becomes the fourth element of the list.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 28 of 41


Fig. 20.10 Inserting node at a specific location of linked list
The steps of algorithm to insert an element at a specific location of linked list is given below.
Algorithm: Insert a Node after specified location
Step 1: If Ptr = NULL
Print “Overflow”
Goto Step 12
End of If
Step 2: Set New_Node = Ptr
Step 3: New_Node → Data = Val
Step 4: Set Temp = Head
Step 5: Set I = 0
Step 6: Repeat Step 5 And 6 Until I
Step 7: Temp = Temp → Next
Step 8: If Temp = NULL
Print "Desired Node Not Present"
Goto Step 12
End of If
End of Loop
Step 9: Ptr → Next = Temp → Next
Step 10: Temp → Next = Ptr
Step 11: Set Ptr = New_Node
Step 12: Exit
The above steps specify that you need to traverse the linked list up to the position – 1 node. You
should know the position where you want to insert the new node. Once all position – 1 node are
traversed then it is possible to allocate the memory and then data for the given nodes. Then point
to the Next pointer of the new node to the Next of the current node. Next point the Next of the
current node to the New Node. In this way, the pointer values of the position – 1 can be changed
and the pointer value of the new node. Once these settings are done then it is possible to insert an
element anywhere in between the linked list.
Summary
 Linked list is a linear collection of the data elements, which are not stored in the
successive memory location.
 Every data element in the linked list will consist of a node which has two parts i.e data
part and pointer part.
 The first part is called as a data part to store data values and second part is called as a
pointer that points to the next element.
 Head is a variable that points to the first element of the linked list and Tail point to the
last element of the linked list.
 Linked list is the dynamic data structure. It is possible to increase the number of elements
of the link list even during the program execution, which is not possible in case of array.
 There are three variants of linked list like Singly, Double and Circular linked list.
 Singly Linked List is the basic linked list in which each node contains data and pointer to
Next element.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 29 of 41


 Doubly Linked list node contains one data part and two pointers instead of one pointer.
The first pointer is left pointer is left pointer to indicate previous node and second pointer
is right pointer to indicate “Next” node.
 Circular Linked List is the list where last node points to first node.
 The various operations that can be performed on linked list are traversing, insertion,
deletion and searching.
 Insertion operation of new node could be in beginning, middle or in the last of the linked
list.
CHECK YOUR PROGRESS
A. Multiple choice questions
1. Linked list is _________ data structure (a) Linear (b) non-linear (c) primary (d) volatile
2. Each element of a linked list is represented as (a) node (b) graph (c) stack (d) link
3. The first element of linked list is called as (a) head (b) tail (c) front (d) leg
4. Finding an element in the list (a) insertion (b) deletion (c) traversing (d) searching
5. In singly linked list, it is possible to traverse the elements only in (a) forward direction (b)
backward direction (c) both A and B (d) None
B. Fill in the Blanks
1. The last element of a linked list is called as _________.
2. Linked list is the _________ data structure.
3. Circular Linked List is a singly linked list where last node points to _________ node.
4. To represent the linked list in memory, _______ arrays are required.
5. Start pointer will point to the _________ element of the linked list.

C. State whether True or False


1. Accessing the elements of linked list is much easier than that of the arrays
2. In a singly linked list, Traversal of items can be done in the backward direction only.
3. The memory requirement for the linked list is less than that of array.
4. It is not possible to insert an element in the middle of the linked list.
5. If the start pointer is equal to NULL then the list is full.
D. Short answer questions
1. What do you mean by Linked list?
2. Write algorithm to perform traversing operation for the linked list.
3. How to insert the element into the linked list at the end?
4. How linked list is represented in memory?
5. Differentiate between singly linked and circular linked list.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 30 of 41


Chapter 21. Tree
Many times, in real life we need to deal with the hierarchical data. For example, in any
organization there are many people working and there is some hierarchy maintained in the post of
these people. The topmost post can be a chief executive officer (CEO) then directors working
under CEO, then managers working under each director and then many more workers working
under the managers as shown in Figure 21.1. Such hierarchical data can be easily handled by
using a data structure called as tree.

Fig. 21.1 Hierarchical data structure tree


In this chapter, you will understand the basic concepts of tree and their types. The binary tree is
discussed with its memory representation and different types.
Tree
Till now we have learned the linear data structures such as arrays, linked list, stack, and queue.
Tree is a nonlinear data structure. It is mainly used for representing the data which contain the
hierarchical relationship among its elements.
A tree is a popular non-linear data structure used in a wide range of applications. It is a collection
of data (Node) which is organized in hierarchical structure recursively. In tree data structure,
every individual element is called as Node. Node in a tree data structure stores the actual data of
that particular element and link to next elements in hierarchical structure. A tree with N number
of nodes has the maximum N-1 number of links.
Records or table of contents can also be represented in the form of trees. A tree is a collection of
zero or more nodes. Out of these nodes one node is called as a root and this tree can have either
zero or one or more sub-trees.
Important key terms for tree data structure
Path − Path refers to the sequence of nodes along the edges of a tree.
Root − The node at the top of the tree is called root. There is only one root per tree and one path
from the root node to any node.
Parent − Any node except the root node has one edge upward to a node called parent.
Child − The node below a given node connected by its edge downward is called its child node.
Leaf − The node which does not have any child node is called the leaf node.
Sub-tree − Sub-tree represents the descendants of a node.
Traversing − Traversing means passing through nodes in a specific order.
Levels − Level of a node represents the generation of a node. If the root node is at level 0, then its
next child node is at level 1, its grandchild is at level 2, and so on.
Keys − Key represents a value of a node based on which a search operation is to be carried out for
a node.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 31 of 41


Fig. 21.2 Tree structure
In Figure 21.2 the node A is the ROOT of the tree having the child B and C. Node B further can
have the child D and E. In the sub-tree, D is a parent node, H and I are the child node. When the
node does not have any child then that node is called as a LEAF. In this Figure 21.2, H, I, J, F, G
are the leaf nodes. Nodes which belong to same parent are called as SIBLINGS like F and G are
siblings. The node which has at-least one child is called as INTERNAL Node. Here B, D, E, C are
the internal nodes. All the nodes are interconnected with each other by edges.
Binary Tree
Binary tree is a tree with each node having at the most two children. It is not possible to have
three children for any node in binary tree.
Figure 21.3 shows a binary tree with root as 1 and two child nodes as 2 and 3. Again the node 2
has two child nodes 5 and 6. The children nodes in the binary tree are named as Left child and
Right child. In this example 5 is the left child and 6 are the right child of node 2.

Fig. 21.3 Binary Tree


Each node of binary tree consists of three parts – data, pointer to the left child and pointer to the
right child. Figure 21.4 shows the first node as the root which will have a pointer to the left child
and pointer to the right child. So, if binary tree is having n nodes then it is confirmed that it will
have in n–1 edge. For example, consider a binary tree with five nodes 1, 2, 3, 5 and 6 as shown in
Figure 21.4. Therefore, it will have 4 edges.

Fig. 21.4 Binary Tree


Every node has one parent and two nodes are connected by single path. For example, the parent
of node 5 and 6 is 2. There is a single path for both the nodes 5 and 6.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 32 of 41


If the height of tree is K then the number of nodes in the binary tree can be given by 2 k+1 – 1 for K
>=0. If you consider the height of this binary tree as 3 then the number of nodes will be 2 3-1=7. It
means at the most this binary tree has seven nodes.
It is also possible to represent algebraic or mathematical expression by a binary tree. A linked list
or array can also be used to represent the binary tree in the memory. Algebraic expression can be
represented by binary tree. Binary tree is represented in memory by linked list or array.
Representation of Binary Tree in Memory
Let us understand how the binary tree is represented in memory. For example, consider a binary
tree as shown in Figure 21.5.

Fig. 21.5 Representation of binary tree using linked list


Suppose first node is the root of the tree with data value A. It will have the two pointers which will
point to the left child and right child. By using the data value, left pointer and right pointer, it is
possible to represent the binary tree using the linked list. The linked list is basically a collection of
nodes and every node consists of the data, the left pointer and right pointer. The left pointer holds
the address of the left child and the right pointer holds the address of the right child. If any sub-
tree of a node is empty then the corresponding pointer of the node will hold a NULL value
indicated by the cross sign as shown in Figure 21.5.
A binary tree can also be represented by an array. For example, consider a binary tree as shown
in Figure 21.6. The value of root node is A in this binary tree. The root node with value A has the
left and right child nodes with value B and C respectively. The node with value B has the left child
with value D and no right child. The node with value C has the left child with value F and right
child with value G. Such binary tree can be represented using array as shown in Figure 21.6.

Fig. 21.6 Representation of binary tree using array


The root with value A is represented with the index 0, the Next value B is represented with index
1, C is represented with index 2 and D is represented with index 3. There is no right child for the
node having value B which is at fifth location with index 4. Therefore, there will be vacancy over
here. The nodes with value F and G are represented with the index 5 and 6 respectively.
When the tree is represented as array, the root is stored at the index value 0. Then the left and
right child of the root are stored in the next subsequent locations. Thus, for a given height K, the
size of the array will be is 2k+1 – 1. Accordingly, the size of array should be declared.
Traversing of Binary Tree (Pre Order, Post Order and In Order)
Traversing operation of the binary tree is just visiting each and every element of the binary tree. It
is possible to perform traversing operation of the binary tree by three ways – Pre-Order, In-Order
and Post-Order.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 33 of 41


Pre-order (NLR)
In pre-order, the sequence of visiting the element is first, node (N), then left sub-tree (L) and then
right sub-tree (R). Algorithm for pre-order traversing is as follows.
Initially process the root R and then traverse the left sub-tree of R in the pre-order and then
traverse the right sub-tree in pre-order. The function pre-order is called to process the sub-tree in
pre-order. So, the algorithm for pre-order processing is as follows.
Algorithm for Pre-order (NLR) traversing
1. Process root N.
2. Traverse left sub-tree of R in pre-order. Pre-order (LST).
3. Traverse right sub-tree of R in pre-order. Pre-order (RST).
For example, consider a binary tree for pre-order traversing, as shown in Figure 21.12. The
sequence of visiting each and every element of the binary tree in pre-order will be 1 then 2 then 4
then 3 then 5 then 7 then 8 then 6.

Fig. 21.12 Traversing of binary tree in Pre-Order (NLR)


In order (LNR)
In in-order traversing, the sequence is the left sub-tree (LST) then the node (N) and then the right
sub-tree (RST). Here the left sub-tree traverse first in in-order then process the root R and then
traverse the right sub-tree in in-order. The function in-order is called to process the sub-tree in
in-order. So, the algorithm for in-order processing is as follows.
Algorithm for Preorder (LNR) traversing
1. Traverse left sub-tree of R in in order. In-order (LST).
2. Process root N.
3. Traverse right sub-tree of R in in order. In-order (RST).
For example, consider a binary tree for in-order traversing, as shown in Figure 21.13. The
sequence of visiting each and every element of the binary tree in In-order will be 4 then 2 then 1
and then move to 7 than 5 then 8 then 3 and then finally the 6.

Fig. 21.14 Traversing of binary tree in In-order (LNR)

Junior Software Developer, Class XI, Unit 4. Data Structure Page 34 of 41


Post-order (LRN)
In post-order traversing, the sequence is the left sub-tree (LST) then the right sub-tree (RST) and
then process the node (N). Here the left sub-tree (LST) traverse first in post-order then the right
sub-tree (RST) traverse in post-order and then the root R is processed in post-order. The function
post-order is called to process the sub-tree in post-order. So, the algorithm for in-order processing
is as follows.
Algorithm for Post-order (LRN) traversing
1. Traverse left sub-tree of R in post-order. Post-order (LST).
2. Traverse right sub-tree of R in post-order. Post-order (RST).
3. Process root N.
For example, consider a binary tree for post-order traversing, as shown in Figure 21.15. The
sequence of visiting each and every element of the binary tree in post-order will be 4 to 2 then 7
then 8 then 5 then 6 then 3 and then finally 1.

Fig. 21.15 Traversing of binary tree in Post-order (LRN)


It is easily observed that in all these three methods the recursive functions are used. In the
algorithm the same function is called again. This method is called as recursion method. Also,
whenever implementing traversing algorithm make use of stack.
Summary
 Tree is a nonlinear data structure.
 A tree is a collection of zero or more nodes.
 All the nodes are interconnected with each other by edges.
 A sub-tree is just nothing but a part of the tree.
 Traversing operation of the binary tree is performed by three ways – Pre-Order, In-Order
and Post-Order.
CHECK YOUR PROGRESS
A. Multiple choice questions
1. Which of the following is non-linear data structure? (a) Stack (b) Queue (c) Array (d) Tree
2. Which of the following data structure is used to represent hierarchical relationship? (a)
Stack (b) Queue (c) Array (d) Tree
3. Number of child nodes of a leaf node are (a) 0 (b) 1 (c) 2 (d) 3
4. A tree in which each node has at the most two children is called (a) Binary tree (b) Full tree
(c) Complete tree (d) AVL tree
5. Height of a Balanced binary tree with n nodes is (a) n+1 (b) 2n (c) n*n (d) log n
B. Fill in the blanks
1. Number of edges in a binary tree of n nodes is ________.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 35 of 41


2. If the height is K then the number of nodes in the binary tree is ________.
3. In a balanced binary tree, both right and left subtree differ by ________level.
4. In a degenerate binary tree, every internal node only has ________child.
5. In pre-order, the sequence of visiting the element is first, root node, then left sub-tree and
then ________ .
C. State whether True or False
1. Root node of a binary tree may have three children.
2. Algebraic or mathematical expression cannot be represented by binary tree.
3. In a complete binary tree, all the levels are completely filled except the last level.
4. Node of a tree which has no parent node is root node.
5. A tree can have cycles.
D. Short answer questions
1. What do you mean by Tree?
2. Write algorithm to perform Pre-order traversal in Binary Tree.
3. Discuss different types of Binary trees?
4. What is In-order traversal of a Binary tree?
5. State the representation of Binary tree in memory.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 36 of 41


Chapter 22. Graphs
Now a days it is quite common that all of us make use of social networks such as Facebook,
Twitter and Linked-in to chat with others. Have you ever thought how the people on the social
networks are connected to each other? You will see that all the people on the social network are
connected to each other by some edges and this can be called as a graph. So, we can say that the
graph is a tool that is used for the connection of the people on the social network.

Fig. 22.1 Graph


In this chapter, you will understand the concept of graphs, its representation in memory, different
terminologies associated with the graph and operations performed on the graph.
Graph
Graph is a non-linear data structure consisting of nodes and edges. Earlier we have seen linear
data structures such as arrays, linked list, stack and queue. The nodes of the graph are called as
the vertices and the lines or arcs of the graph are called as edges.
A graph is represented as G = (V, E), where V is the set of vertices and E is the set of edges.
For example, a graph shown in Figure 22.2 has 5 vertices and all these vertices are connected to
each other by the edges or lines. In this graph, the vertices are A, B, C, D and E and the edges are
(A, B), (A, E), (B, C), (B, D), (B, E), (C, D) and (D, E).

Fig. 22.2 Edges and vertices of graph


Graphs are very useful data structure to solve many real-world applications. They are used to
represent network such as telecommunication network and circuit network. Graphs are used in
social network where each person is represented by a vertex or node. The node will contain the
information such as name, gender, and address of the person.
Google map also makes the use of graph. Every location on the Google map is represented by the
vertices. Graph are used to find the shortest distance between any two locations on the Google
map.
Terminologies related to Graph
Let us understand some terminologies associated with Graph in Figure 22.3.
Vertex – Each node in the graph is called as vertex.
Edge – Path between two vertices is called as edge and it is represented by adjacent vertices. For
example, A is connected to the B so there is an edge between A and B similarly there is an edge
between C and G as shown in Figure 22.3.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 37 of 41


Weighted Edge – In many applications, each edge of a graph has an associated numerical value,
called a weight. Usually, the edge weights are nonnegative integers. Weighted graphs may be
either directed or undirected. Observe edge I to L has weight 42.
Adjacency – Two vertices are adjacent to each other when they are connected to each other by
edge. For example, A and B are adjacent, A and D are adjacent and A and E are also adjacent.
Loop – Whenever an edge starts from some vertex and at the end reach to the same vertex then it
forms a loop. For example, start from K to J, J to L, then L to H and then come back to K. This is
called as a loop of the graph.
Path – A sequence of edges between two vertices is called as path. For example, K to J, J to L,
then L to I is the path from K to I.
Connected Graph – when there is a path from any vertex to every other vertex then it is called as
connected graph. When there is no any isolated vertex which is not connected to the other vertices
then that graph can be called as a connected graph.
Degree of vertex – Number of incident edges is called as degree of vertex.
For example, A has 3 edges and therefore the degree of the vertex A is 3. Isolated vertex will not
have any connection edge between the other vertices and hence it has degree 0. The pendent
vertex has only one edge to the other vertex, hence it has degree 1.

Fig. 22.3 Terminologies related to Graph


Types of graph
A graph can be undirected, directed and cyclic graph, as shown in Figure 22.4.

Fig. 22.4 Types of graph

Junior Software Developer, Class XI, Unit 4. Data Structure Page 38 of 41


In undirected graph the edges do not have a particular direction. In directed graph the edges will
have a direction. In directed graph, it is possible to traverse the graph in particular direction.
When it is possible to reach the same vertex after traveling or visiting the other vertex of the
graph, then it is called as cyclic graph.
Representation of Graph
There are two methods to represent a graph in memory. The first method is called as the
sequential representation. In this method, it is necessary to create the adjacency matrix for the
given graph to represent it in memory.
Another way to represent the graph is the linked representation. In this method the graph is
represented by making the use of the linked list.
The adjacency matrix A for graph G = (V, E) with n vertices. The adjacency matrix is n×n matrix,
such that
Aij = 1, if there is an edge from Vi to Vj and
0, if there is no edge
For example, consider a graph as shown in Figure 22.5. There is an edge from A to B, from A to E
and therefore you will find that from A to B there is there is 1 represented in the adjacency matrix
and from A to E the 1 is being represented while the others are represented by the number 0.
Similarly, edge from B to A then B to E and B to C and therefore the corresponding element in the
adjacency matrix is represented by 1 and other elements are represented by 0. In this way we can
prepare the adjacent matrix for any given graph.

Fig. 22.5 Sequential representation of graph


In the linked representation, it is necessary to create the adjacency list and then represent the
Graph by making the use of this list.
For example, consider a graph as shown in Figure 22.6, where A is connected to B and B is
connected to D. Therefore, it can have a pointer from A to B and from B to D. Then the pointer of
the D will hold a NULL value. Similarly, from B there are edges to A, D and C and therefore it can
have a pointer from B to A, then to D and then to C. The pointer value for the node of C will have
a NULL value. In this way the adjacency list for any given graph is prepared. This adjacency list
can be represented by making the use of the linked list and this matrix can be represented by
making the use of two-dimensional array.

Fig. 22.6 Linked representation of graph


Operations of Graph
The following operations can be performed on graph.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 39 of 41


 Traversing – This is the most common operation performed on the graph, where each and
every node of the graph is visited.
 Searching – This operation finds the location of the node N in the graph.
 Insertion – Adding node N in a graph is known as insertion.
 Deletion – Removing node from a graph is known as deletion.
 Merging of Vertices – Two or more vertices are merged with each other.
 Spitting of Vertices – Split one vertex into two or more vertices.
 Edge contraction – Edges of a graph can be contracted.
Traversing – This is the most common operation performed on the graph, where each and every
node of the graph is visited. For example, consider a graph as shown in Figure 22.6.

Fig. 22.7 Traversing a Graph


In this traversing operation, start from the level 0 with a root and then go on visiting each and
every element. You can start from any node and then go on visiting each and every node of the
graph. As shown in Figure 22.6, start from A then go to B → C → D → E → F → G and finally to
H. In this way traversing of the graph is performed.
Summary

 Graph is a non-linear data structure consisting of nodes and edges.


 A graph is represented as G = (V, E), where V is the set of vertices and E is the set of
edges.
 Graphs are very useful data structure to solve many real-world applications.
 Graphs are used in social network where each person is represented by a vertex or node.
 Graph are used to find the shortest distance between any two locations on the Google
map.
 Each node in the graph is called as vertex.
 Path between two vertices is called as edge and it is represented by adjacent vertices.
 Two vertices are adjacent to each other when they are connected to each other by edge.
 Whenever an edge starts from some vertex and at the end reach to the same vertex then it
forms a loop in graph.
 Number of incident edges is called as degree of vertex.
 A graph can be undirected, directed or cyclic graph.
 There are two ways to represent Graph in memory, first is sequential representation and
second is linked representation.
 Sequential representation uses adjacency matrix while linked representation uses linked list
data structure.
 The Operations that can be performed on graph are Traversing, Searching, Insertion, Dele-
tion, Merging of Vertices, Spitting of Vertices and Edge contraction.
CHECK YOUR PROGRESS
A. Multiple Choice Questions
1. Which of the following is non-linear data structure? (a) Stack (b) Queue (c) Array (d) Graph

Junior Software Developer, Class XI, Unit 4. Data Structure Page 40 of 41


2. Which of the following data structure is used to represent social network connections? (a)
Stack (b) Queue (c) Tree (d) Graph
3. Each node in the graph is called (a) Edge (b) Vertex (c) Link (d) Connection
4. A sequence of edges between two vertices is called (a) Vertex (b) Path (c) Link (d)
Connection
5. If there is a path from any vertex to every other vertex in a graph then it is called (a)
connected graph (b) full graph (c) NULL graph (d) directed graph
B. Fill in the Blanks
1. Number of incident edges is called as ________ of vertex.
2. When it is possible to reach the same vertex after traveling or visiting the other vertex of
the graph, then it is called as _________ graph.
3. Adjacency matrix represent the connection of _________ in a graph.
4. In adjacency matrix A of a Graph, Aij = _________, if there is an edge from Vi to Vj.
5. It is possible to traverse the graph in particular direction in ________ graph.
C. State whether True or False
1. Google map makes the use of the graph.
2. Computer network can be represented by a graph.
3. If there is no edge from a node to another node in a graph, corresponding entry in
adjacency matrix will be 0.
4. Linked list can be used to represent a graph.
5. A graph cannot have cycles.
D. Short answer questions
1. What do you mean by Graph?
2. State the representation of Graph in memory.
3. Discuss different operations on Graph.
4. Illustrate edge, path and loop in a graph with example.
5. Write the difference between directed and undirected graph.

Junior Software Developer, Class XI, Unit 4. Data Structure Page 41 of 41

You might also like