Data Structures Using C
Data Structures Using C
UNIT-I Basic Concepts: Pointers and dynamic memory allocation, Algorithm-Definition and
characteristics, Algorithm Analysis-Space Complexity, Time Complexity, Asymptotic Notation
Introduction to Data structures: Definition, Types of Data structure, Abstract Data Types (ADT),
Difference between Abstract Data Types, Data Types, and Data Structures. Arrays-Concept of Arrays,
Single dimensional array, Two dimensional array, Operations on arrays with Algorithms (searching,
traversing, inserting, deleting)
UNIT-II Linked List: Concept of Linked Lists, Representation of linked lists in Memory, Comparison
between Linked List and Array, Types of Linked Lists - Singly Linked list, Doubly Linked list, Circularly
Singly Linked list, Circularly Doubly Linked list; Implementation of Linked List ADT: Creating a List,
Traversing a linked list, Searching linked list, Insertion and deletion into linked list (At first Node-
specified Position, Last node), Application of linked lists
UNIT-III Stacks: Introduction to stack ADT, Representation of stacks with array and Linked List,
Implementation of stacks, Application of stacks - Polish Notations - Converting Infix to Post Fix
Notation - Evaluation of Post Fix Notation - Tower of Hanoi, Recursion: Concept and Comparison
between recursion and Iteration Queues: Introduction to Queue ADT, Representation of Queues with
array and Linked List, Implementation of Queues, Application of Queues Types of Queues- Circular
Queues, De-queues, Priority Queue
UNIT-IV Searching: Linear or Sequential Search, Binary Search and Indexed Sequential Search
Sorting: Selection Sort, Bubble Sort, Insertion Sort, Quick Sort and Merge Sort
UNIT-V Binary Trees: Concept of Non- Linear Data Structures, Introduction Binary Trees, Types of
Trees, Basic Definition of Binary Trees, Properties of Binary Trees, Representation of Binary Trees,
Operations on a Binary Search Tree, Binary Tree Traversal, Applications of Binary Tree.
Graphs: Introduction to Graphs, Terms Associated with Graphs, Sequential Representation of Graphs,
Linked Representation of Graphs, Traversal of Graphs (DFS, BFS), Application of Graphs.
1
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
UNIT-I
Data Structures
Introduction
Data Structure can be defined as the group of data elements which provides an efficient way of storing and
organizing data in the computer so that it can be used efficiently.
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.
Basic Terminology:
Data structures are the building blocks of any program or the software. Choosing the
appropriate data structure for a program is the most difficult task for a programmer.
Following terminology is used as far as data structures are concerned
Data: Data can be defined as an elementary value or the collection of values, for example,
student's name and its id are the data about the student.
Group Items: Data items which have subordinate data items are called Group item, for example,
name of a student can have first name and the last name.
Record: Record can be defined as the collection of various data items, for example, if we talk
about the student entity, then its name, address, course and marks can be grouped together to form
the record for the student.
File: A File is a collection of various records of one type of entity, for example, if there are 60
employees in the class, then there will be 20 records in the related file where each record contains
the data about each employee.
Attribute and Entity: An entity represents the class of certain objects. it contains various
attributes. Each attribute represents the particular property of that entity.
Field: Field is a single elementary unit of information representing the attribute of an entity.
2
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Data Types
A data type is a term which refers to the kind of data that may be appear in the calculation.
The result of the calculation is depends on the type of data used in the calculation.
Data type specifies set of values and set of operations defined on them.
For example with numbers we perform addition, subtraction, multiplication, division operations and
with strings we perform concatenation, extraction operations.
3
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
User
Abstract Data
(Or)
Programmer
Operations
Examples:
1. Arrays
2. Stacks
3. Queues
4. Trees
5. Lists
Abstract Data
Type
User
Abstract Data
(Or)
Programmer
Operations
Common ADTs:
1. Arrays
2. Stacks
3. Queues
4. Trees
5. Graphs
4
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
1. Array:
An array is a collection of similar data items which share common name. The elements of
an array are accessed using a number called “Index”. The index of the first element is 0 and the
index of the last element is [Link] elements are stored in a sequential memory locations.
2. Stack:
Stack is a linear list of elements in which elements are inserted and deleted at the same end
called top of the stack. Stacks are also called LIFO (Last In First Out) lists, since the last inserted
element is removed first.
PUSH POP
TOP
ADT stack
{
Data
Linear list of elements
Operations
Push(): Inserts a new element at the top of the stack
5
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
10 20 30 40 50 60
Insert
Delete
FRONT REAR
ADT queue
{
Data:
Linear list of elements
Operations:
Insert(): Inserts a new element at rear end of the queue
Delete(): Removes an element from the front end of the queue
Top(): Retutns an element located at top of the stack
}
4. Trees:
Tree is a non-linear list of elements made up of nodes or vertices and edges without having
any cycle.
A Root Node
Parent Node
B C
D E F G Child Node
ADT tree
{
Data:
Non linear list of elements
Operations:
Insert(): Inserts a new node to the tree
Delete(): Removes a node from the tree
Search(): Returns the location of the specified node
6
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
}
5. Graph:
Graph is a non-linear list of elements made up of nodes or vertices and edges with having
any cycle.
ADT tree
{
Data:
Non linear list of elements
Operations:
Insert(): Inserts a new vertex to a graph
Delete(): Removes a node from the graph
Search(): Returns the location of the specified node
}
Data Structures
A data structure is a specialized format for collecting, organizing, storing and retrieving data in an
effective way.
The logical or mathematical model of a particular organization of data is called a data structure.
Data structure is a programming construct used to implement an ADT.
Data structure is a physical implement of ADT.
A data structure that implements an ADT consists collection of variables to store data and the
collection of algorithms or functions to implement operations.
Types of Data Structures:
8
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Index 0 1 2 ………………. Size-1
ADT array
{
Data:
Linear list of elements
Operations:
lowerbound(): returns the index of first element
upperbound(): Returns the index of last element
size(): Returns size of the array
index(element): Returns the index of specified element.
}
ii. Linked list:
Linked list is a linear list of elements represented as nodes. Each node in a linked
list contains two parts: data part and link part. The data part contains value of the node and the link
part contains address of the next node. Linked lists are called dynamic data structures since the
nodes are created whenever necessary at the time of executing the program.
ADT Linked list
{
Data:
Collection of nodes
Operations:
Insert(): inserts a new node.
Delete():deletes the specified node.
size(): Returns size of the list.
Traverse():visits all the nodes in the list.
}
iii. Stack:
Stack is a linear list of elements in which elements are inserted and deleted at the same end
called top of the stack. Stacks are also called LIFO (Last In First Out) lists, since the last inserted
element is removed first.
PUS POP
H
TOP
9
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
ADT stack
{
Data
Linear list of elements
Operations
Push(): Inserts a new element at the top of the stack
Pop(): Removes an element from top of the stack
Top(): Retutns an element located at top of the stack
}
[Link]:
Queue is a linear list of elements in which elements are inserted at one end called “Rear”
end and elements are deleted from another end called “Front” end. Queues are also called FIFO
(First In First Out) lists,since the first inserted element is removed first.
10 20 30 40 50 60
Insert
Delete
FRONT REAR
ADT queue
{
Data:
Linear list of elements
Operations:
Insert(): Inserts a new element at rear end of the queue
Delete(): Removes an element from the front end of the queue
Top(): Retutns an element located at top of the stack
}
(b) Non-linear data structures:
A data structure is said to be non-linear data structure if its elements are not in a sequence.
Non-Linear data structure is opposite to linear data structure.
In non-linear data structure, the data item is connected to several other data items.
It uses memory efficiently. Free contiguous memory is not required for allocating data
items.
10
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
A Root Node
Parent Node
B C
D E F G Child Node
ADT tree
{
Data:
Non linear list of elements
Operations:
Insert(): Inserts a new node to the tree
Delete(): Removes a node from the tree
Search(): Returns the location of the specified node
}
ii. Graphs:
Graph is a non-linear list of elements made up of nodes or vertices and edges with
having any cycle.
ADT tree
{
Data:
Non linear list of elements
Operations:
Insert(): Inserts a new vertex to a graph
Delete(): Removes a node from the graph
Search(): Returns the location of the specified node
}
Algorithms
An algorithm can be defined as a finite set of steps, which has to be followed while carrying out a
particular problem. It is nothing but a process of executing actions step by step.
An algorithm is a distinct computational procedure that takes input as a set of values and results in
the output as a set of values by solving the problem. More precisely, an algorithm is correct, if, for
each input instance, it gets the correct output and gets terminated.
11
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
An algorithm unravels the computational problems to output the desired result. An algorithm can
be described by incorporating a natural language such as English, Computer language, or a
hardware language.
Characteristics of Algorithms:
o Input: It should externally supply zero or more quantities.
o Output: It results in at least one quantity.
o Definiteness: Each instruction should be clear and ambiguous.
o Finiteness: An algorithm should terminate after executing a finite number of steps.
o Effectiveness: Every instruction should be fundamental to be carried out, in principle, by a person
using only pen and paper.
o Feasible: It must be feasible enough to produce each instruction.
o Flexibility: It must be flexible enough to carry out desired changes with no efforts.
o Efficient: The term efficiency is measured in terms of time and space required by an algorithm to
implement. Thus, an algorithm must ensure that it takes little time and less memory space meeting
the acceptable limit of development time.
o Independent: An algorithm must be language independent, which means that it should mainly
focus on the input and the procedure required to derive the output instead of depending upon the
language.
Advantages of an Algorithm:
o Effective Communication: Since it is written in a natural language like English, it becomes easy
to understand the step-by-step delineation of a solution to any particular problem.
o Easy Debugging: A well-designed algorithm facilitates easy debugging to detect the logical errors
that occurred inside the program.
o Easy and Efficient Coding: An algorithm is nothing but a blueprint of a program that helps
develop a program.
o Independent of Programming Language: Since it is a language-independent, it can be easily
coded by incorporating any high-level language.
Disadvantages of an Algorithm:
o Developing algorithms for complex problems would be time-consuming and difficult to
understand.
o It is a challenging task to understand complex logic through algorithms.
Algorithm Analysis
In the analysis of the algorithm, it generally focused on CPU (time) usage, Memory usage, Disk
usage, and Network usage.
All are important, but the most concern is about the CPU time.
Be careful to differentiate between:
12
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Performance: How much time/memory/disk/etc. is used when a program is run. This depends on
the machine, compiler, etc. as well as the code we write.
Complexity: How do the resource requirements of a program or algorithm scale, i.e. what happens
as the size of the problem being solved by the code gets larger.
Algorithm analysis is an important part of computational complexity theory, which provides
theoretical estimation for the required resources of an algorithm to solve a specific
computational problem.
Analysis of algorithms is the determination of the amount of time and space resources required
to execute it.
Complexity
o Time Complexity of an algorithm is the representation of the amount of time required by the
algorithm to execute to completion.
o Time requirements can be denoted or defined as a numerical function t(N), where t(N) can be
measured as the number of steps, provided each step takes constant time.
o For example, in case of addition of two n-bit integers, N steps are taken.
o Consequently, the total computational time is t(N) = c*n, where c is the time consumed for
addition of two bits.
o Here, we observe that t(N) grows linearly as input size increases.
o In other words, the time complexity is how long a program takes to process a given input.
o The efficiency of an algorithm depends on two parameters:
Time Complexity
Space Complexity
Time Complexity: It is defined as the number of times a particular instruction set is executed
rather than the total time is taken. It is because the total time took also depends on some external
factors like the compiler used, processor’s speed, etc.
Space Complexity: It is the total memory space required by the program for its execution.
13
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Big oh Notation (O)
For example:
If f(n) and g(n) are the two functions defined for positive integers,
then f(n) = O(g(n)) as f(n) is big oh of g(n) or f(n) is on the order of g(n)) if there exists constants c
and no such that:
14
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Arrays
Definition:
An array is a collection of elements of same type that share a common name. (OR) An array is a
collective name given to a group of similar quantities.
The elements of an array are stored in contiguous memory locations.
Elements of an array can be accessed through a number called “Index”.
The index of a first element is ‘0’ and the index of the last element is ‘size-1’.
The memory is allocated to an array is depend on its type and size.
Address of the first array element is called “base address”.
Advantages:
1. An array reduces the usage of number of variables in a program.
2. It maintains a list of values with a single name
3. An array is used for searching operations
4. It is used to sort a list of values
5. It is useful for matrix operations
Types of Arrays:
In ‘C language, arrays are classified into two types. They are
1. One Dimensional Arrays
2. Multi Dimensional Arrays
ONE DIMENSIONAL ARRAY:-
When an array is declared with only one dimension (subscript) then it is called “One dimensional
array” or “single dimensional array”.
Declaring One Dimensional Array:
Syntax: datatype arrayname[size];
In the above syntax,
The datatype is any data type of C language. An array can hold all the values based on the data
type.
The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements use this
variable name.
The ‘size’ indicates maximum number of elements of an array. It must be a positive integer
constant.
Example-1: int a[5];
The above declaration reserves 5 contiguous memory locations of integer type for the array
‘num’. The memory representation is as shown below:
15
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
1001 1003 1005 1007 1009
Base Address
Example-2: float marks[50];
Example-3: char name[10];
Accessing elements of one dimensional array:
A one dimensional array element is accessed by specifying the array name followed by index. The
array indexes can be from 0 to size-1 of the array.
The index must be positive integer. The index value must be enclosed within square brackets.
It can be a constant, variable or an expression.
Examples Meaning
1. num[0] To access 1st element of array
2. num[4] To access 5th element of array
3. num[i] To access ith element of array. If i=2 then it is num[2]
4. num[i+2] To access i+2 element of array. If i=2 then it is num[2+2] i.e. num[4]
ii) Assigning Values: Storing values in an arrary after the declaration is called “assigning”
Example: main()
{
int num[10];
num[0]=120;
num[5]=245;
}
16
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
In the above example, 120 is assigned to num[0] element, and 245 is assigned to num[5] element.
The remaining elements contain garbage values.
iii) Inputting Values: We can give values to the elements of an array using input statements.
Examples Meaning
1. scanf(“%d”,&num[0]) ; To input value to num[0]
2. scanf(“%d%d”,&num[0],&num[4]) ; To input values to num[0] and num[4]
3. scanf(“%d”,&num[i]); To input value to num[i]. If i=2 then it is num[2]
4. for(i=0;i<=4;i++) To input values from num[0] to num[4] at once i.e. 5 elements.
scanf(“%d”,&num[i]);
TWO-DIMENSIONAL ARRAYS
When an array is declared with two dimensions then it is called “two-dimensional array”. A two-
dimensional array is an array of one-dimensional arrays.
It can be viewed as table of elements which contains rows and columns. A two-dimensional array
is useful for matrix operations.
Declaring Two-Dimensional Array:
17
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Syntax: datatype arrayname[rowsize][columnsize];
In the above syntax,
i. The datatype is any valid data type of C language. An array can hold all the values based on the
data type.
ii. The ‘arrayname’ is an identifier that specifies name of the array variable. All the elements use this
variable name.
iii. The ‘rowsize’ indicates maximum number of rows and ‘columnsize’ indicates number of columns
in a row.
Example:
int num[2][3];
Here, it reserves 6 (2 rows x 3 columns) integer type memory locations for the array ‘num’. The
memory representation is as shown below:
num[2][3]
0 1 2
0
1
Accessing Elements Of Two Dimensional Array
A two dimensional array element is accessed by specifying the array name followed by two
subscripts. The array indexes can be from 0 to size - 1 of the array.
Each subscript must be positive integer. The subscript values must be enclosed within square
brackets. It can be a constant, variable or an expression.
Examples Meaning
num[0] [0] To access 1st element of array
num[1][2] To access 2nd row and 3rd column element of array
num[i][j] To access ith row, jth column of array. If i=1,j=2 then it is num[1][2]
num[i+2][j+1] To access i+2,j+1 element of array. If i=1,j=2 then it is
num[1+2][2+1] i.e. num[3][3]
18
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
i) Initialisation of Two Dimensional Array: Storing values to an array at the time of declaring an
array is called initializing array.
Here, if we omit values then an array contains garbage values. The number of values must
be less than or equal to the size of the array. When there are few values then the remaining
elements are assigned with zeros.
Example-1: int num[2][3] = { {4, 6, 8}, {1, 3, 5}}; num 0 1 2
0 4 6 8
1 1 3 5
num 0 1 2
0 4 8 0
1 5 0 0
Example-2:
int num[2][3] = { {4, 8}, {5}};
ii) Assigning Values: Storing values in an arrary after the declaration is called “assigning”
Example: main()
{
int num[10][10];
num[0][0]=120;
num[5][4]=245;
}
In the above example, 120 is assigned to num[0][0] element, and 245 is assigned to num[5][4]
element. The remaining elements contain garbage values.
iii) Inputting Values: We can give values to the elements of an array using input statements.
Examples Meaning
1. scanf(“%d”,&num[0][0]); To input value to num[0][0]
2. scanf(“%d%d”,&num[0][0],&num[1][2]); To input values to num[0][0] and num[1][2]
3. scanf(“%d”,&num[i][j]); To input value to num[i][j]. If i=1,j=2 then it is
num[1][2]
4. for(i=0;i<=1;i++) To input values from num[0][0] to num[1][2] at
for(j=0;j<=2;j++) once i.e. 6 elements.
scanf(“%d”,&num[i][j]);
19
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
ARRAY OPERATIONS
An array is a finite collection of similar elements stored in adjacent memory locations. An array is ‘finite’
means it contains specific number of elements and ‘similar’ means that all the elements are of the same data type.
The array operatiosn are:
Searching
Traversing
Inserting
Deleting
Searching:
Searching means finding the location of any item in the array. Suppose A is a linear array with n elements.
The simplest way to search for a given item is to compare the item with each element in A one by one. That is,
first we test A[0] = item, and then we test A[1] = item and so on. The algorithm is:
1: Set LOC = 0
2: Repeat step 3 while LOC < N3: If A[LOC] = ITEM then
goto step 4
Else
Set LOC = LOC + 1
4: Print LOC, ITEM
5: Exit
Traversing:
Let ‘A’ be a collection of data elements stored in the computer’s memory. To print the contents of each
element of A, we have to be accessed at least once. This is called traversing. Thealgorithm is:
1: Set I = LB
2: Repeat steps 3 and 4 while I <= UB3: Print A[I]
4: Set I = I + 1
5: Exit
Inserting:
Insertion means adding a new element to the array. If an element is inserted at the end of the array, then
the task is easily done. But if we need to insert an element in the middle of an array then half of the elements must
be moved forward to new locations to put up the new element. The algorithm is:
1: Set J = UB
2: Repeat step 3 and 4 while J >= POS3: Set A[J + 1] = A[J]
4: Set J = J - 1
5: Set A[POS] = ITEM
6: Set UB = UB + 1
7: Exit
20
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Deleting:
Deletion means removing an element from the array. Deleting the element from the end of array is not a
problem. But deleteing from the middle of an array requires moved of each element backward to fill up the empty
space in the array. The algorithm is:
4: Set UB = UB-1
5: Exit
POINTERS
Definition: A pointer is a variable that holds the memory address of another variable. It is used to
access value of a variable quickly.
Uses or Advantages of Pointers:
1. Execution of program will be faster.
2. Array elements can be easily accessed.
3. It provides call-by-reference mechanism.
4. We can send arrays and strings to functions.
5. Memory can be efficiently used through dynamic memory allocation (DMA).
6. Dynamic data structures like linked list, binary trees and graphs can be created.
Declaring a Pointer Variable:
A pointer declaration contains a base type(data type) and asterisk (*) followed by a variable.
A pointer variable is an unsigned integer and hence it occupies 2 bytes of memory.
Syntax: datatype *variable;
Example: Pointer variable P Q Simple Variable
int Q=50; Value of P (or)
1625 50
int *P; Address of Q Value of Q
P = &Q;
Address of P 2956 1625 Address of Q
POINTER OPERATORS:
‘C’ language provides two special operators to manipulate the values directly from memory using pointer
variables.
21
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
2. Indirection Operator (*): The asterisk (*) character is a unary operator that returns the value
stored at the memory address.
Syntax: Variable=*pointer variable;
Dynamic Memory Allocation (DMA)
Dynamic Memory Allocation means allocation of memory at run-time i.e. during the program execution.
DMA technique is useful when it is not known how much memory space is required before executing the
program.
‘C’ language provides various standard functions to manage memory efficiently.
Memory Management Functions:
malloc( ) Function:
It allocates memory space to a variable. The space must be specified in the form of bytes.
This function returns NULL if the allocation of memory fails.
It means, if the memory is not sufficient to allocate then it returns NULL.
The general format of malloc( ) function is as follows:
Syntax: pv = (type *) malloc(size);
Example-1:
int *p;
p = (int *) malloc(4); Allocates 4 bytes of memory to the variable ‘p’.
Example-2:
int *p, n=5;
p = (int *) malloc(n*2); Allocates memory for 5*2=10 bytes to p.
calloc( ) Function: This function is also used to allocate space to a variable. But it initializes all the elements with
zero.
Syntax: pv = (type *) calloc(n, size);
Example-1: int *p;
p = (int *) calloc(5, 4); 20 bytes allocated to p and 4 bytes for each block
22
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
UNIT – II
LINKED LISTS
LINKED LIST
Linked list is the most commonly used data structure used to store same data elements inthe memory.
The elements of a linked list are not stored in adjacent memory locations as in arrays.
A linked list is a linear collection of data elements called nodes. Each node contains two [Link], Data
field and Link field.
Node
Data Link
Data field contains the element of the list and link field contains the address of the next node.
In linked lists, each node is connected by using the links.
Linked lists are dynamic data structure, i.e. we can insert or delete nodes whenever werequired.
Advantages:
Linked list can be increased or decreased because of dynamic data structure.
Linked list are dynamic, which allocates the memory when required.
Insertion and deletion can be easily performed.
Disadvantages:
It occupies more space because every node contains a link field to store the address of thenext node.
The elements are accessed sequentially, i.e. from the head node to tail node. No element canbe accessed
randomly.
23
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
By using linked lists we cannot access a node directly like we can with an array (a[5] for example). To get to node
5 in a linked list, we must start with the first node called "head", use that node's pointer to get to the next node,
and do so while keeping track of the number of nodes we have visited until we reach node 5.
Array is a fixed size, so arrays cannot be increased or decreased during execution. For example, if we have
allocated space for 5 elements and try to add more than 5 elements we are not able to do. Simillarly if we have
allocated space for 5 elements but are not using the whole space, the unused space goes waste.
The elements in an array are stored in continuous memory locations, but in many cases the continuous memory
space is not available.
The operations like insertion and deletion after the specified position may be difficult. It requires each element
after the specified position to be moved one position forward (insertion) or one position backward (deletion).
Arrays are stored in continuous memory Linked lists are not stored in continuousmemory
locations. locations.
Elements are accessed sequentially or randomly. Elements are accessed only sequentially.
Insertion and deletion operation takes time. Insertion and deletion operation is faster
24
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
TYPES OF LINKED LISTS
Linked List:
A linked list is a linear collection of data elements called nodes. Each node contains two fields. Namely,
Data field and Link field. Data field contains the element of the list and link field contains the address of the next
node. In linked lists, each node is connected by using the links. Linked lists are dynamic data structure, i.e. we can
insert or delete nodes whenever we required. There are mainly three types of linked lists. They are:
N1 N2 N3 N4 N5
The Data field contains the element of the list, Left Link field contains the address of theprevious node and
Right Link field contains the address of the next node.
In doubly linked list, the nodes are connected with two links.
We maintain a pointer called Headptr to store the address of first node of the lsit.
In doubly linked list, we can travel both directions either from Head node to Tail node or Tailnode to Head
node. Hence it is also called as two-way list.
Head Node Tail Node
Headp tr N 10 20 30 N
N1 N2 N3
25
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
In a circular singly linked list, the nodes are connected with one link.
We maintain a pointer called Headptr to store the address of first node of the list.
Head Node Tail Node
Headp
tr 10 20 30
Array is a collection of elements having same Linked list is an ordered collection of elements
data type with common name. which are connected by links.
Array elements can be stored in consecutive Linked list elements can be stored at any available
manner in memory. place as address of node is stored in previous node.
Insert and delete operation takes more time in Insert and delete operation cannot take more time.
array. It performs operation in fast and in easy way.
It can be single dimensional, two dimensional or It can be singly, doubly or circular linked list.
multidimensional.
Each array element is independent and does not Location or address of element is stored in the link
26
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
have a connection with previous element or with part of previous element or node.
its location.
Array elements cannot be added, deleted once it The nodes in the linked list can be added and
is declared. deleted from the list.
In array, elements can be modified easily by In linked list, modifying the node is a complex
identifying the index value. process.
Pointer cannot be used in array. So, it does not Pointers are used in linked list. Elements are
require extra space in memory for pointer. maintained using pointers or links. So, it requires
extra memory space for pointers.
27
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
UNIT- 3
Representations of Stack:
There are two methods to represent stacks in the memory.
1. Array Representation
2. Linked Representation
1. Array Representation:
In the aray representation a stack is represented using a one-dimensional array.
Array representation is used when the stack contains fixed number of elements.
The right end of an array is considered as top end where we perform both push and pop operations.
The index of last element in an array is called top.
Initially top points to one position less than the lower bound to indicate stack is empty.
28
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
i. Infix=a+b
ii. Prefix=+ab
iii. Post-fix=ab+
4. Stacks are used to traverse a graph with DFS method (Depth First Search).
5. stacks are used in reversing numbers and strings.
6. stacks are used in calling of multiple functions.
7. Stacks are used to evaluate towers of Hanoi problem.
8. stacks are used in back tracking.
9. Operating system internally uses a stack to manage different kinds of processes.
10. Operating system internally uses a stack in memory management.
Stacks in Recursion
Recursion in stack ADT:-
A recursive function is defined as a function that calls itself to solve a smaller version of its task until a
final call is made which does not require a call to itself. Since a recursive function repeatedly calls itself, it
makes use of the system stack to temporarily store the return address and local variables of the calling
function. Every recursive solution has two major cases. They are
Base case, in which the problem is simple enough to be solved directly without making any
further calls to the same function.
Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Therefore, recursion is defining large and complex problems in terms of smaller and more easily solvable
problems. In recursive functions, a complex problem is defined in terms of simpler problems and the simplest
problem is given explicitly.
To understand recursive functions, let us take an example of calculating factorial of a number. To calculate n!
We multiply the number with factorial of the number that is 1 less than that number. In other words, n! = n X
(n–1)!
Let us say we need to find the value of 5! 5! = 5 X 4 X 3 X 2 X 1
= 120
This can be written as
5! = 5 X 4! Where 4! = 4 X 3!
Therefore,
5! = 5 X 4 X 3!
Similarly, we can also write, 5! = 5 X 4 X 3 X 2!
Expanding further
5! = 5 X 4 X 3 X 2 X 1!
31
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
We know, 1! = 1
The series of problems and solutions can be given as shown in Fig.
Now if you look at the problem carefully, we can write a recursive function to calculate the factorial of a
number. Every recursive function must have a base case and a recursive case. For the factorial function
Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
Recursive case of the factorial function will call itself but with a smaller value of n, this case can be given as
factorial (n) = n × factorial (n–1).
#include<stdio.h>
long int fact( int n);
main()
{
long int f;
clrscr();
f=fact(6);
printf(“factorial=%l”,f);
}
long int fact( int n)
{
if ( n <= 1 )
return (1) ;
else
return ( n * fact ( n-1) );
Output:
} Factorial=720
32
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Queues
Queue:
Queue is a linear list of elements in which the elements are inserted at one end called REAR end and deleted
at the same end called FRONT end .Queues are also called FIFO(First In First Out) lists since the first
inserted element is removed first.
Insert
Delete 10 20 30 40 50 60
FRONT REAR
ADT of a queue:
AbstractDataType Queue
{
Instances
Ordered list of elements
Operations :
Empty():Returns true if the queue is [Link] it returns false.
Size():Returns number of elements in the queue.
Front():Returns front end of the queue.
Rear():Returns rear element (last) of the queue.
insert(x):adds the element ‘x’ at the rear end of the queue.
delete():Remove an element from the front end of the queue.
}
Representations of queue:
There are two methods of queue representations. They are
1. Array Representation
2. Linked Representation
1. Array Representation:
A queue is represented using one-dimensional array when a queue contains fixed number of elements.
The right end of the array is considered as rear end and the left end of an array is considered as front
end.
While adding items to the queue the rear end of the queue is increased, while deleting items from the
queue the front end of the queue is increased.
Initially both front and rear points to -1 which indicates queue is empty.
If we add an element to the queue for the first time, the front and rear points to zero.
33
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
If the values of front and rear are equal than the queue contains only one element.
Algorithm for queue insert():
34
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Applications of Queues:
Queues are used to represent graphs with BFS method(Breadth First Search).
Queues are used in process scheduling.
Queues are used in first come first serve applications.
Queues are used in network applications.
Queues are used while uploading images to the server and downloading images from the server.
Queues are used in call center phone system.
Queues are used in online reservation system (railway reservation, bus tickets).
Queues are used in memory buffer management.
Queues are used in input, output management.
Queues are used to maintain the inbox and outbox contents of e-mail.
Circular queue
35
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
The limitation of simple queue is insertion will not be allowed even if there are some vacant locations
at front of the queue.
To overcome the limitation of simple queue we use a circular queue.
In a circular queue the rear end is connected back to the front end to make a circle.
The operations are performed in the circular queue based on First In First Out Method(FIFO)
Like a simple queue elements are interested in the rear end and the elements are deleted from the front
end.
36
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
37
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
DE Queue
DE queue stands for Double Ended Queue
DE Queue is one kind of queue in which both insertion and deletion operations are performed at both
front end and rear end.
DE Queue is also called head and tail queue.
Insert Insert
Delete Delete
Front Rear
38
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Insert
Delete Delete
Front Rear
Insert Insert
Delete
Front Rear
addAtRear(item) addAtFront(item)
if(rear=length-1) then if(front=0) then
print “DE Queue is overflow” print “DE Queue is overflow”
return return
else else
if front=-1 then if front=-1 then
front=rear=0 front=rear=0
else else
rear=rear+1 front=front-1
Endif Endif
DQ[rear]=item DQ[front]=item
Endif Endif
39
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
DeleteFromFront() DeleteFromRear()
return return
else else
front=rear=-1 front=rear=-1
else else
front=front+1 rear=rear-1
Endif Endif
Endif Endif
Priority queue
A priority queue is an abstract data type that behaves similarly to the normal queue except that
each element has some priority, i.e., the element with the highest priority would come first in a priority queue.
The priority of the elements in a priority queue will determine the order in which elements are
removed from the priority queue.
The priority queue supports only comparable elements, which means that the elements are either
arranged in an ascending or descending order.
For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an ordering
imposed on the values is from least to the greatest. Therefore, the 1 number would be having the highest
priority while 22 will be having the lowest priority.
Characteristics of a Priority queue:-
1, 3, 4, 8, 14, 22
All the values are arranged in ascending order. Now, we will observe how the priority queue will look after
performing the following operations:
poll(): This function will remove the highest priority element from the priority queue. In the
above priority queue, the '1' element has the highest priority, so it will be removed from the
priority queue.
add(2): This function will insert '2' element in a priority queue. As 2 is the smallest element
among all the numbers so it will obtain the highest priority.
poll(): It will remove '2' element from the priority queue as it has the highest priority queue.
add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it will obtain the
third highest priority in a priority queue.
Types of Priority Queue
40
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
[Link] order priority queue: In ascending order priority queue, a lower priority number is given as a
higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in an ascending order like
1, 2, 3, 4, 5; therefore, the smallest number, i.e., 1 is given as the highest priority in a priority queue.
[Link] order priority queue: In descending order priority queue, a higher priority number is given as
a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in descending order like
5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the highest priority in a priority queue.
Applications of Queues
42
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
UNIT-IV
SEARCHING AND SORTING
Example:
43
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
List: 10 14 19 26 27 31 33 35 42 44
Searching element: 27
Binary Search
Binary search is a fast searching method when compared to other searching methods.
This search method works on the principle of divide and conquers method.
This searching method works properly on the sorted data.
Binary search looks a particular element by comparing middle most element in the list.
If a middle element is a searching element the index of the middle element is returned.
If the middle element greater than the searching element, then the element is searched in the sub list to
the left of the middle element.
If the middle element is less than the searching element, then the element is searched in the sub list to
the right of the middle element.
This process is continued up to the sub list size becomes zero.
Algorithm:
BinarySearch (A:list of sorted elements,K:element to be searched)
n=length(A)
lower bound=1
upper bound=n
while true
44
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
if upperbound<lowerbound then
print ”element not found”
return
end if
mid=(lowerbound+upperbound)/2
if A[mid]>k then
lowerbound=mid+1
else
if A[mid]>k then
upperbound=mid-1
else
if A[mid]=k then
print “element found at ”+mid
return
end if
end if
end if
end while
Example:
List 10 14 19 26 27 31 33 35 42 44
Element to be search k=42
1st Pass
1 2 3 4 5 6 7 8 9 10
10 14 19 26 27 31 33 35 42 44
2ndpass
1 2 3 4 5 6 7 8 9 10
31 33 35 42 44
Third pass
1 2 3 4 5 6 7 8 9 10
42 44
45
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Mid
upperbound
lowerbound
Mid =(lpwer bound+upper bound)/2
=(9+10)/2
=19/2
=9
42=42 Element found at mid i.e=8
Sorting
Sorting: Sorting is a mechanism of arranging the data either in ascending or descending order. All the sorting
methods performs the following two steps.
[Link] two values.
[Link] two values.
Sorting techniques:
[Link] sort
[Link] sort
[Link] sort
[Link] sort
[Link] sort
[Link] sort or bucket sort
[Link] sort
Bubble sort
Bubble Sort is a simple sorting method used to sort a given set of elements.
Bubble Sort compares all the elements one by one and sort them based on their values.
Bubble sort will start by comparing the first element with the second element, if the first element is
greater than the second element, it will swap both the elements, and then move on to compare the
second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 passes.
In each pass each pair of adjacent elements are compared and swapped if they are not in order.
In the 1st pass the first maximum fixed at nth position. In the second pass the second maximum fixed at
n-1th position. This process is continued for n-1 passes.
In each pass bubble sort makes n-i comparisons where n is number of elements and i is the pass
number.
Advantages:
Easy to understand.
Easy to implement.
In-place, no external memory is needed.
Performs greatly when the elements are almost sorted.
Disadvantages
It does more element assignments.
46
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Slow in process
It does not deal well with a list containing a huge number of items.
Not suitable for real life applications.
Algorithm:
Bubblesort( A: List of elements)
n=length(A)
for i= 1 to n-1
for j=1 to n-i
if(A[j]>A[j+1]) then
temp=A[j]
A[j]=A[j+1]
A[j+1]=temp
End if
End for
End for
Return A
Elements before Sorting:
54 26 93 17 31 44 55 20
1st Pass
Element
s after
Sorting:
17 20 26 31 44 54 55 20
47
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Selection Sort
Selection sort improves on bubble sort by reducing number of swapping but number of comparisons
and passes remains same.
Selection sort makes n-1 passes and make one swap in each pass.
This sorting is also comparison based sorting technique in which the list is divided into two parts:
sorted part and unsorted part.
Sorted part is located at left and unsorted part is located at right side.
Initially sorted part is empty and unsorted part is entire list.
In the first pass the first minimum is fixed at the first position of the sorted part.
In the second pass the second minimum is fixed at the second position of the sorted part.
This process is continued up to unsorted part becomes empty.
Elements before Sorting:
54 26 93 17 31 44 55 20
1st Pass
Ele
me
nts
Aft
er
Sor
ting
:
54 26 93 17 31 44 55 20
48
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Advantages:
Easy to understand.
Easy to implement.
In-place, no external memory is needed.
Minimum number of swappings.
Disadvantages
It does more element assignments.
Slow in process.
Poor efficiency when dealing with a huge list of items.
Not suitable for real life applications.
Algorithm:
SelectionSort( A: List of elements)
n=length(A)
for i= 1 to n-1
min=i
for j=i+1 to n-1
if(A[min]>A[j]) then
min=j
End if
End for
If i≠min then
temp=A[i]
A[i]=A[min]
A[min]=temp
End if
End for
Return A
Insertion sort
Insertion sort is a simple and efficient sorting method than bubble sort and selection sort.
This sorting method reduces number of comparisons and number of swapping than bubble sort and
selection sort.
This method is useful and best when the number of elements in the list is small.
It can also be useful when the list is almost sorted [Link] few elements are misplaced.
This is an in-place comparison based sorting method in which the list is divided into two parts: sorted
and unsorted part.
The sorted part is at left side and the unsorted part is at right side.
Initially the left part contains first element and the right part contains the remaining elements.
In the first pass the second element is inserted in its appropriate place in the sorted part(left part).In the
second pass the third element is inserted in its appropriate place in the sorted part.
49
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Advantages:
It is simple to implement.
It is efficient on small data values.
It is efficient on data nearly sorted.
It is efficient when number of elements is small.
Disadvantages:
It is less efficient if the list contains more number of elements.
If the number of elements is increased the program would be slow.
Algorithm:
Insertion(A:list of elements)
n=length(A)
for i=2 to n
temp=A[i]
j=i
while(j>1 && A[j-1] >=temp)
A[j]=A[j-1]
J=j-1
End while
A[j]=temp
End for
Return A
50
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Merge Sort
Merge sort is a sorting technique based on divide and conquer method.
Merge sort divides the list into equal parts and then combine them in a sorted manner.
This sorting method requires additional memory space for storing sub lists before merging.
However merge sort is effective while sorting huge amount of data.
Advantages:
Uses fewer comparisons than the quick sort.
Stable when the list contains similar elements.
Stable when the list is already sorted.
Stable when the list contains huge amount of data.
Disadvantages:
Extra memory space is required.
Time consuming sorting.
Algorithm:
51
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Quick
sort
Quick sort is most advanced sorting and complicated sorting than other sorting methods.
The basic concept in quick sort is to pick one element in the list as a pivot, around which the other
elements are rearranged.
Everything less than the pivot is moved to the left of the pivot.
Everything greater than the pivot is moved to the right of the pivot.
At this point each partition is recursively quick [Link] left and right side partitions are again
partitioned into sub partitions with two pivots.
This process will be continued upto the elements are arranged in a sorted order.
Quick sort is the fastest sorting method because it uses divide and conquer method.
Algorithm:
1. Choose a pivot value: Take any value as a pivot in the list.
2. Partition:
The elements which are less than the pivot place them at left side of the pivot.
The elements which are greater than the pivot place them at right side of the pivot.
3. Sort both sides: Apply quick sort algorithm for both left and right side partitions.
52
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Advantages:
Fastest sorting technique.
In-place, no external memory is needed.
Performs greatly when list contains huge amount of data.
Disadvantages:
Difficult to partition.
Efficiency of sorting is depends on the pivot selection.
Example:
53
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
UNIT-V
TREE DEFINITION:
Tree is a hierarchical Or Non-linear data structure which stores the information naturally in the form of
hierarchy style.
Tree is one of the most powerful and advanced data structures.
It is a non-linear data structure compared to arrays, linked lists, stack and queue.
It represents the nodes connected by edges.
The above figure represents structure of a tree. Tree has 2 sub trees.
A is a parent of B and C.
B is called a child of A and also parent of D, E, F.
BASIC TREE TERMINOLOGY :
o Root: The root node is the topmost node in the tree hierarchy. In other words, the root node is the one
that doesn't have any parent. In the above structure, node numbered 1 is the root node of the tree. If a
node is directly linked to some other node, it would be called a parent-child relationship.
o Child node: If the node is a descendant of any node, then the node is known as a child node.
o Parent: If the node contains any sub-node, then that node is said to be the parent of that sub-node.
o Sibling: The nodes that have the same parent are known as siblings.
o Leaf Node:- The node of the tree, which doesn't have any child node, is called a leaf node. A leaf
node is the bottom-most node of the tree. There can be any number of leaf nodes present in a general
tree. Leaf nodes can also be called external nodes.
o Internal nodes: A node has atleast one child node known as an internal
54
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
o Ancestor node:- An ancestor of a node is any predecessor node on a path from the root to that node.
The root node doesn't have any ancestors. In the tree shown in the above image, nodes 1, 2, and 5 are
the ancestors of node 10.
o Descendant: The immediate successor of the given node is known as a descendant of a node. In the
above figure, 10 is the descendant of node 5.
Advantages of Tree
Tree reflects structural relationships in the data.
It is used to represent hierarchies.
It provides an efficient insertion and searching operations.
Trees are flexible. It allows to move subtrees around with minimum effort.
Definition:
"A tree in which every node can have maximum of two children is called as Binary Tree."
The above tree represents binary tree in which node A has two children B and C. Each children have
one child namely D and E respectively.
55
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Array index is a value in tree nodes and array value gives to the parent node of that particular index or
node.
Value of the root node index is always -1 as there is no parent for root.
When the data item of the tree is sorted in an array, the number appearing against the node will work
as indexes of the node in an array.
Binary search tree is a binary tree which has special property called BST.
BST property is given as follows:
For all nodes A and B,
I. If B belongs to the left subtree of A, the key at B is less than the key at A.
II. If B belongs to the right subtree of A, the key at B is greater than the key at A.
I. Parent (P), left, right which are pointers to the parent (P), left child and right child respectively.
Definition:
"Binary Search Tree is a binary tree where each node contains only smaller values in its left subtree and only
56
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
The above tree represents binary search tree (BST) where left subtree of every node contains smaller values
and right subtree of every node contains larger value.
Binary Search Tree (BST) is used to enhance the performance of binary tree.
It focuses on the search operation in binary tree.
Note: Every binary search tree is a binary tree, but all the binary trees need not to be binary search trees.
1. Insert Operation:
Insert operation is performed with O(log n) time complexity in a binary search tree.
Insert operation starts from the root node. It is used whenever an element is to be inserted.
The following algorithm shows the insert operation in binary search tree:
Step 1: Create a new node with a value and set its left and right to NULL.
Step 4: If the tree is not empty, check whether a value of new node is smaller or larger than the
node (here it is a root node).
Step 5: If a new node is smaller than or equal to the node, move to its left child.
Step 6: If a new node is larger than the node, move to its right child.
57
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
The above tree is constructed a binary search tree by inserting the above elements {50, 80, 30, 20,
100, 75, 25, 15}. The diagram represents how the sequence of numbers or elements are inserted into
a binary search tree.
2. Search Operation :
Search operation is performed with O(log n) time complexity in a binary search tree.
This operation starts from the root node. It is used whenever an element is to be searched.
The following algorithm shows the search operation in binary search tree:
Step2: Compare this element with the value of root node in a tree.
Step 3: If element and value are matching, display "Node is Found" and terminate the function.
Step 4: If element and value are not matching, check whether an element is smaller or larger than a node
value.
Step 7: Repeat the same process until we found the exact element.
Step 8: If an element with search value is found, display "Element is found" and terminate the function.
Step 9: If we reach to a leaf node and the search value is not match to a leaf node, display "Element is not
found" and terminate the function.
58
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
1. Preorder Traversal:
Algorithmforpreordertraversal
Step1: StartfromtheRoot.
Step2: Then,gototheLeftSubtree.
Step3: Then,gototheRightSubtree.
Step 2 : A + B + D (E + F) + C (G + H)
Step 3 : A + B + D + E + F + C + G + H
Preorder Traversal : A B C D E F G H
59
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
The above figure represents how post order traversal actually works.
Step 1 : As we know, preorder traversal starts from left subtree (last leaf) ((Postorder on E + Postorder on F)
+ D + B )) + ((Postorder on G + Postorder on H) + C) + (Root A)
Step 2 : (E + F) + D + B + (G + H) + C + A
Step 3 : E + F + D + B + G + H + C + A
Postorder Traversal : E F D B G H C A
3. In order Traversal:
60
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Step 3 : B + E + D + F + A + G + C + H
Inorder Traversal : B E D F A G C H
o The height of the tree is defined as the longest path from the root node to the leaf node. The tree which
is shown above has a height equal to 3. Therefore, the maximum number of nodes at height 3 is equal
to (1+2+4+8) = 15. In general, the maximum number of nodes possible at height h is (2 0 + 21 +
22+….2h) = 2h+1 -1.
o If the number of nodes is minimum, then the height of the tree would be maximum. Conversely, if the
number of nodes is maximum, then the height of the tree would be minimum.
As we know that,
n = 2h+1 -1
n+1 = 2h+1
log2(n+1) = log2(2h+1)
log2(n+1) = h+1
h = log2(n+1) - 1
61
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
As we know that,
n = h+1
h= n-1
Applications of trees
o Storing naturally hierarchical data: Trees are used to store the data in the hierarchical structure. For
example, the file system. The file system stored on the disc drive, the file and folder are in the form of
the naturally hierarchical data and stored in the form of trees.
o Organize data: It is used to organize data for efficient insertion, deletion and searching. For example,
a binary tree has a logN time for searching an element.
o Trie: It is a special kind of tree that is used to store the dictionary. It is a fast and efficient way for
dynamic spell checking.
o Heap: It is also a tree data structure implemented using arrays. It is used to implement priority
queues.
o B-Tree and B+Tree: B-Tree and B+Tree are the tree data structures used to implement indexing in
databases.
o Routing table: The tree data structure is also used to store the data in routing tables in the routers.
62
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
GRAPHS
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links.
The interconnected objects are represented by points termed as vertices, and the links that
connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of
edges, connecting the pairs of vertices.
In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23,
34, 04, 14, 13}.
Take a look at the following graph −
Mathematical graphs can be represented in data structure. We can represent a graph using an array
of vertices and a two-dimensional array of edges.
63
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Nodes: These are the most important components in any graph. Nodes are entities whose
relationships are expressed using edges. If a graph comprises 2 nodes A and B and an
undirected edge between them, then it expresses a bi-directional relationship between the
nodes and edge.
Vertex − Each node of the graph is represented as a vertex. In the following example, the
labeled circle represents vertices. Thus, A to G are vertices. We can represent them using
an array as shown in the following image. Here A can be identified by index 0. B can be
identified using index 1 and so on.
Edge − Edge represents a path between two vertices or a line between two vertices. In the
following example, the lines from A to B, B to C, and so on represents edges. We can use
a two-dimensional array to represent an array as shown in the following image. Here AB
can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping
other combinations as 0.
Adjacency − Two node or vertices are adjacent if they are connected to each other through
an edge. In the following example, B is adjacent to A, C is adjacent to B, and so on.
Path − Path represents a sequence of edges between the two vertices. In the following
example, ABCD represents a path from A to D.
Basic Operations:
Types of Graphs
Directed Graph:
64
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
The first element of the pair V1 is called the start vertex and the second element of the pair V 2 is
called the end vertex.
Undirected Graph:
Set of Edges E = {(1, 2), (1, 3), (1, 5), (2, 1), (2, 3), (2, 4), (3, 4), (4, 5)}
Applications of Graphs:
65
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
66
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
The above graph represents undirected graph with the adjacency matrix representation. It
shows adjacency matrix of undirected graph is symmetric. If there is an edge (2, 4), there is
also an edge (4, 2).
The above graph represents directed graph with the adjacency matrix representation.
It shows adjacency matrix of directed graph which is never symmetric.
If there is an edge (2, 4), there is not an edge (4, 2). It indicates direct edge from vertex i to
vertex j.
67
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
In adjacency list, an entry array[i] represents the linked list of vertices adjacent to the
ith vertex.
Adjacency list allows to store the graph in more compact form than adjacency matrix.
It allows to get the list of adjacent vertices in O(1) time.
Disadvantages of Adjacency List:
68
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
A tree has one path joins any two vertices. A spanning tree of a graph is a tree that:
Contains all the original graph’s vertices.
Reaches out to (spans) all vertices.
Is acyclic. In other words, the graph doesn’t have any nodes which loop back to itself.
A Spanning tree can be defined as a subset of a graph, which consists of all the vertices
covering minimum possible edges and does not have a cycle. Spanning tree cannot be
disconnected.
Every connected and undirected graph has at least one spanning tree.
A disconnected graph does not have a spanning tree as it is not possible to include all
vertices.
There are two most popular algorithms that are used to find the minimum spanning tree in a
graph.
They include:
Kruskal’s algorithm
Prim’s algorithm
Kruskal’s Algorithm
Kruskal’s algorithm is an algorithm to find the MST in a connected graph.
Prim’s Algorithm
Prim’s algorithm is yet another algorithm to find the minimum spanning the tree of a graph.
In contrast to Kruskal’s algorithm that starts with graph edges, Prim’s algorithm starts with
a vertex.
We start with one vertex and keep on adding edges with the least weight till all the vertices
are covered.
69
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Step 5 : Pop the top node from stack and change status of the node.
Step 6 : Push all the neighbouring nodes and change their status is weighting.
Step 7 : Stop
Breadth First Search(BFS) :- Breadth first search involves for choosing a node from the point. These
process continues until we reach null node. It uses the queue operations. The algorithm whichis used to
implements breadth first search method is as follows.
70
III SEM BSC DR C V RAMAN DEGREE COLLEGE DATA STRUCTURES USING C
Algorithm : BFS
Step 1: Start
Step 7 : Stop
71
DR. C V RAMAN DEGREE COLLEGE III SEM BSC DATA STRUCTURES USING C
72