Bbaca Sem III Datastructure
Bbaca Sem III Datastructure
1) Declaration of a Pointer:
data type *pt_name; This tells the compiler three things about the variable pt_name:
Ø The asterisk (*) tells that the variable pt_name is a pointer variable.
The initialization of the pointer variable is simple like other variable but in the pointer variable the address is
assigned to the pointer variable instead of value.
Once a pointer has been assigned the address of a variable, one can access the value of the
variable using unary operator ‘*‘(asterisk), known as the indirection operator or dereferencing
operator.
C) Dynamic Memory Allocation:
The technique through which a program can be obtaining space in the RAM
during the execution of the program and not during compilation is called
dynamic memory allocation. The entire runtime view of memory for a
program is given below:
Functions of Dynamic Memory Allocation:
1) malloc() function:
malloc() function is used for allocating block of memory at runtime. This function reserves a block of
memory of given size and returns a pointer of typo void. This means that one can assign it to any
type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.
2) calloc() function:
calloc() is another memory allocation function that is used for allocating memory at runtime. calloc()
initializes the allocated memory to zero but, malloc() doesn’t. calloc() function is normally used for
allocating memory to derived data types such as arrays and structures. If it fails to locate enough
space it returns a NULL pointer.
3) realloc() function:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to new
size. If enough space doesn’t exist in memory of current block to extend, new block is allocated for
the full size of reallocation, then copies the existing data to new block and then frees the old block.
4) free() function:
When a program comes out, operating system automatically release all the memory allocated by the
program but as a good practice when there is no need of memory anymore then the memory should
be released by calling the function free().free() function frees the allocated memory by malloc (),
calloc (), realloc () functions and returns the memory to the system.
1.2 Algorithm-Definition and characteristics
Definitions:
1) Alonzo Church and Alan Turing:
“An algorithm is defined as the finite sequence of instructions, each of which has a clear meaning and
can be performed with a finite amount of effort in a finite length of time.”
2) David Hilbert:
“An algorithm is a set of instructions designed to perform a specific task.”
Characteristics of Algorithm:
1) Finiteness:
An algorithm must terminate after a finite number of steps.
2) Definiteness:
The steps of the algorithm must be precisely defined or unambiguously specified.
3) Correctness:
The output must be true for all input values.
4) Generality:
An algorithm must be generic enough to solve all problems of a particular class.
1.3 Algorithm Analysis :
Space Complexity & Time Complexity
Analysis of Algorithm:
1) Considerations in Algorithm Analysis:
Analysis of algorithms focuses on computation of space and time complexity. Space can be
defined in terms of space required to store the instructions and data whereas the time is the
computer time an algorithm might require for its execution which usually depends on the
size of the algorithm and input.
a) Space Complexity:
The space complexity of a problem is a related concept that measures the amount of space,
or memory required by the algorithm. Space complexity is measured with Big-O notation.
b) Time Complexity:
Time Complexity is defined as the computer time an algorithm might require for its
execution, which usually depends on the size of the algorithm and input.
2) Types of Time Complexities:
i) Big-oh or “O"-Notation:
O-notation is used to expressing the upper bound of an
algorithms running time.
g(n) is a given function, O (g (n)) is a set of function n, then it
is given as:
O(g(n)) = { f(n) : there exist positive constants c and n0such
that ,
0 ≤ f(n)≤ c*g(n) , for all n ≥ n0 } .
ii) θ-notation:
g (n) is a given function and θ(g (n)) is the set of functions
then, (g (n)) = { f(n) : there exist positive constants c1, c2 and
n0 such that , 0 ≤ c1 g(n) ≤ f(n) ≤ c2 g(n) ,for all n ≥ n0 }.
iii) Ω-notation:
Ω-notation is used for asymptotic lower bound. For a given
function g (n),Ω(g (n)) as the set of functions ,Ω (g(n)) = { f ( n) :
there exist positive constants c and n0 such that 0 ≤ c * g(n) ≤ f(n ) ,
for all n ≥ n0 }
iv) o-notation or ‘little oh’:
o-notation is used to denote an upper bound that is not
asymptotically tight. It is also called ‘little oh’.o(g (n)) = { f(n) :
For any positive constant c >0, there exists constant n0> 0 such
that 0≤ f(n) ≤ cg (n), for all n ≥ n0 }.The function f (n) becomes
insignificant relative to g(n) as n approaches infinity,
v) Little-Omega Notation:
It is denoted by ω-notation. ω- Notation is used to denote a
lower bound that is not asymptotically tight (g (n)) = {f (n): For
any positive constant c > 0, if a constant n0> 0 such that, 0≤ cg
(n) ≤ f (n), for all n ≥ n0 }.
Introduction to Data Structure
A data structure in Computer Science, is a way of storing
and organizing data in a computer’s memory or even disk
storage so that it can be used efficiently.
A well-designed data structure allows a variety of critical
operations to be performed.
Data structures are implemented by programming
language by the data types, references and operations
provide by that particular language.
Different kinds of data structures are suited to different
kinds of applications, and some are highly specialized to
certain tasks.
1.5 DATA STRUCTURE AND ITS TYPES
Basically, data structures are of two types
linear data structure and non linear data structure.
1. Linear data structure :
A data structure is said to be linear if the elements form a
sequence i.e., while traversing sequentially, we can reach only
one element directly from another.
For example : Array, Linked list,Queue etc.
2. Non linear data structure :
Elements in a nonlinear data structure do not form a sequence i.e
each item or element may be connected with two or more other
items or elements in a non-linear arrangement. For example :
Trees and Graphs etc.
DATA STRUCTURE OPERATIONS
We come to know that data structure is used for the
storage of data in computer so that data can be used
efficiently.
The data manipulation within the data structures are
performed by means of certain operations.
The following four operations play a major role on data
structures.
a) Traversing : Accessing each record exactly once so that
certain items in the record may be processed. (This
accessing and processing is sometimes called “visiting” the
record.)
b) Searching : Finding the location of the record with a
given key value, or finding the locations of all records,
which satisfy one or more conditions.
c) Inserting : Adding a new record to the structure.
d) Deleting : removing a record from the structure.
Sometimes two or more of these operations may be used in a
given situation.
For example, if we want to delete a record with a given key
value, at first we will have need to search for the location of the
record and then delete that record.
The following two operations are also used in some special
situations :
i) Sorting : Operation of arranging data in some given order,
such as increasing or decreasing, with numerical data, or
alphabetically, with character data.
ii) Merging : combining the records in two different sorted files
into a single sorted file.
1.5 Abstract Data Type
A) Meaning:
v An Abstract Data Type (ADT) is a mathematical model of the data
objects that make up a data type as well as the functions that operate on
these objects.
v An abstract data type is the specification of logical and mathematical
properties of a data type or structure.
v ADT acts as a useful guideline to implement a data type correctly. The
specification of an ADT does not imply any implementation
consideration.
v The implementation of an ADT involves the translation of the ADT`s
specification into syntax of a particular programming language.
v Thus, ADT involves mainly two parts:
a) Description of the way in which components are related to each
other.
b) Statements of operations that can be performed on that data
Array : Introduction
The fundamental data types namely int, float, char etc. are very useful but variable of these
data type can be stored only one value at a time. So they can handle limited amount of
data. In many applications we need to handle large volume of data for that we have to need
powerful data types that would facilitate efficient storing, accessing and manipulation of
data items.
C supports derived data type known as Array.
Definition-
An array is collection of data items of the same data type
An array is fixed-size sequenced collection of elements of the same data type.
An array is also called as Subscripted Variables
Features of Array:
An array is a collection of similar elements.
The location of array is the location of its first element.
The first element in array is numbered zero so the last element is less than the size of array.
The length of array is the number of its elements in array.
The type of an array is the data type of its element.
An array is known as subscripted variable.
Before using array it’s type and dimension must be declared.
1.6 Types of Array 1.Single Dimension Array :
A list of items can be given one variable name using only one subscript and
such a variable is called a single subscripted or single Dimension Array.
Syntax :
data type arrayname[size];
Example :
int rollno[3];
float marks[5];
char name[30];
0 1 2
100 101 102
R1 2 73
R2 3 82
R3 4 90
R4 5 58
Example :
char name[10];
It declares the name as a character array (string) variable that can hold a
maximum 10 characters. Each character of the string is treated as an element of
the array name and is stored in the memory as follows.
‘W’ ‘E’ ‘L’ ‘’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
The above representation can be modified to incorporate number of terms present in a polynomial
by reserving the 0thlocation of the array for this purpose. The modified representation is shown in
below figure. A general polynomial can be represented in an array with descending order of its
degree of terms. Therefore, the operations such as addition, multiplication and division on
polynomials can be easily carried out.
A generic polynomial is of the form: p(x) = anxn + an-1 xn-1 + an-2 xn-
2+ ........a x2 + a x + a It is assumed that the coefficient values of a
2 1 0. 0
through an are all known and constant and will be stored in an array.
Thus, the evaluation of a polynomial has only the value of x as its input
and will return the resulting polynomial value as its output. An
alternative method of writing the polynomial is :
p(x) x = a0 + a1x+ a2 x2 + …….+ an-1 xn-1+ anxn
= a0 + x (a1 + x (a2 + x (a3 + x (a4+….x(an-1 + x an)))))
The method requires only n multiplication and n additions. The
polynomial evaluation can be performed by evaluating the expression
in the innermost parenthesis and successfully multiplying by x in for
loop. The coefficients a0, a1, a2, ... an are stored in an array a[n].
Addition of Polynomial:
When adding polynomials only the coefficients of same powerare added and subtracted, the
exponents remain unchanged. While adding two polynomials, following cases need to be
considered.
1) When the Degrees of Corresponding Terms of the Two Polynomials are
Same:
This is the normal case when corresponding coefficients of each term can be added
directly.
Example:
5x3+2x2+7
7x3+9x2+12
12x3+11x2+19 is a simple addition where all the degrees of the corresponding terms are
same.
2) When the degrees of corresponding terms of the polynomials are different:
The terms with of same power are added but of different powers remain as it is.
9x4+5x3+ 2x
3x4+4x2+7x
12x4+5x3+4x2+9x
Multiplication of Polynomials:
In general, when multiplying two polynomials together, the
distributive property is used, i.e.every term of one polynomial is
multiplied with every term of the other polynomial. After that the
answer is simplified by combining the like terms. In the following
example every term of poly 2 will multiply with every term of poly 1.
Coefficients get multiplied and power gets added.
Poly 1: 5x^3 + 3x^2+2
Poly 2: 3x^2+5x+4
After multiplying, the result is
15x^5 + 9x^4 + 6x^2 + 25x^4 + 15x^3 + 10x + 20x ^3 + 12x^2 +
8
Simplifying the answer by adding the like terms,
Multiplication result: 15x^5 + 34x^4 + 35x^3 + 18x^2 + 10x + 8
1.7 Structure :
Arrays can store many values of a similar data type. Data in the array is of the same composition
in nature as far as the type is concerned. To maintain employee’s information one should have
information such as name, age, qualification, salary and so on. Name and qualification of the
employee are char data type, age is an int and salary is float. All these data types cannot be
expressed in a single array. One may think to declare different arrays for each data type, but
there will be huge increase in source codes of the program. Hence, arrays cannot be useful here.
For tackling such a mixed data type problems, a special feature is provided by C known as a
structure.
Example: A structure of type book 1 is created. It consists of three
members: book [30] of char data type, pages of int type and price of float
data type. Figure explains various members of a structure.
struct book1
{
char book[30] ;
int pages;
float price;
};
struct book1 bk1; Block Diagram of a Structure
1.8 Self-Referential Structure:
b) Declaration of Linked Structure:
The linked structure given in abovefigure can be obtained by the following steps:
Declare structure chain.
Declare variables A and B of type chain.
p(A) = B
These steps have been coded in the program segment given below:
struct chain /* declare structure chain */
{
int val;
chain *p:
};
struct chain A, B; /* declare structure variables A and B
A.p = &B; /* Connect A to B
B.p = NULL;
The data elements in this linked structure can be assigned as follows:
A.val= 50;
B.val =60;
The linked structure now looks like as shown in figure.
d) typedef keyword:
The C programming language provides a keyword called typedef, which is used to give a type a new
name. typedef can be used to give a name to user defined data type. To use typedef with structure
define a new data type and then use that data type to define structure variables directly.
Example: typedef unsigned char BYTE;
After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsigned
char,for example BYTE b1, b2;
1.8 Self-Referential Structure:
When a member of a structure is declared as a pointer to the structure itself then the structure is called self-
referential structure.
struct chain
{
Intval;
struct chain *p;
};
The structure called ‘chain’ consists of two members: val and p. The member val is a variable of type int whereas
the member p is a pointer to a structure of type chain. Thus, the structure chainhas a member that can point to a
structure of type chain or may be itself .This type of self-referencing structure can be viewed as shown in Figure.
Linked Structure
Unit 2 Linear Data Structure
2.1 Introduction to Array – array representation
2.2 Sorting algorithms with efficiency
- Bubble sort,
- Insertion sort,
- Merge sort,
- Quick Sort,
- Selection Sort
2.3 Searching techniques –
1. Linear Search
2. Binary search
2.1 Introduction to Array- array representation
The fundamental data types namely int, float, char etc. are very useful but variable of these
data type can be stored only one value at a time. So they can handle limited amount of
data. In many applications we need to handle large volume of data for that we have to need
powerful data types that would facilitate efficient storing, accessing and manipulation of
data items.
C supports derived data type known as Array.
Definition-
An array is collection of data items of the same data type
An array is fixed-size sequenced collection of elements of the same data type.
An array is also called as Subscripted Variables
Features of Array:
An array is a collection of similar elements.
The location of array is the location of its first element.
The first element in array is numbered zero so the last element is less than the size of array.
The length of array is the number of its elements in array.
The type of an array is the data type of its element.
An array is known as subscripted variable.
Before using array it’s type and dimension must be declared.
Single Dimension Array :
A list of items can be given one variable name using only one subscript and
such a variable is called a single subscripted or single Dimension Array.
Syntax :
data type arrayname[size];
Example :
int rollno[3];
float marks[5];
char name[30];
0 1 2
100 101 102
1340 1342 1344 ----- Memory Address
Array elements are always stored in contiguous memory locations and since the
data type int occupies 2 bytes of memory, each element will be allocated 2 bytes.
Declaration and Initialization Array :
We can initialise elements of array in the same way the ordinary variable.
Syntax :
data type arrayname[size]={list of values};
Example :
int rollno[5]={1,2,3,4,5};
int rollno[ ]={1,2,3,4,5};
float num[5]={2.5,7.2,9.2,6.2,3.3};
Multi Dimension Array :
An array whose elements are speacified by more than one subscript is known as multi
dimension array (also called Matrix)
Syntax :
data type arrayname[row size][column size];
Example :
int student[5][2];
C0 C1
R0 1 67
R1 2 73
R2 3 82
R3 4 90
R4 5 58
Example :
char name[10];
It declares the name as a character array (string) variable that can hold a
maximum 10 characters. Each character of the string is treated as an element of
the array name and is stored in the memory as follows.
‘W’ ‘E’ ‘L’ ‘’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
Employee No.
Employee Name
Employee Salary
Department Name
Here, employee no. can be takes as key for sorting the records in ascending or descending order. Now,
we have to search a Employee with employee no. 116, so we don't require to search the complete
record, simply we can search between the Employees with employee no. 100 to 120.Sorting Techniques
Sorting technique depends on the situation. It depends on two parameters.
1. Execution time of program that means time taken for execution of program.
2. Space that means space taken by the program.
The above diagram represents how insertion sort works. Insertion sort works like the way we sort
playing cards in our hands. It always starts with the second element as key. The key is compared with the
elements ahead of it and is put it in the right place.
In the above figure, 40 has nothing before it. Element 10 is compared to 40 and is inserted before 40.
Element 9 is smaller than 40 and 10, so it is inserted before 10 and this operation continues until the
array is sorted in ascending order.
3. Merge sort
Merge sort is one of the most efficient sorting algorithms. It works on the principle of Divide and
Conquer. Merge sort repeatedly breaks down a list into several sublists until each sublist consists of a
single element and merging those sublists in a manner that results into a sorted list.
4. Quick Sort
5. Selection Sort
Selection sort is a simple sorting algorithm which finds the smallest element in the array
and exchanges it with the element in the first position. Then finds the second smallest
element and exchanges it with the element in the second position and continues until the
entire array is sorted.
2.3 Searching Techniques (Linear and Binary Search)
What is Searching?
Searching is the process of finding a given value position in a list of values.
It decides whether a search key is present in the data or not.
It is the algorithmic process of finding a particular item in a collection of
items.
It can be done on internal data structure or on external data structure.
Searching Techniques
To search an element in a given array, it can be done in
following ways:
1. Linear/sequential Search
2. Binary Search
1. Sequential Search
Sequential search is also called as Linear Search.
Sequential search starts at the beginning of the list and checks every
element of the list.
It is a basic and simple search algorithm.
Sequential search compares the element with all the other elements given
in the list. If the element is matched, it returns the value index, else it
returns -1.
Binary searching starts with middle element. If the element is equal to the element that we are
searching then return true. If the element is less than then move to the right of the list or if the
element is greater than then move to the right of the list. Repeat this, till you find an element.
3. Linked List
3.1 Introduction to Linked List
3.2 Implementation of Linked List – Static & Dynamic
representation,
3.3 Types of Linked List
- Singly Linked list(All type of operation)
- Doubly Linked list (Create , Display)
- Circularly Singly Linked list (Create, Display)
- Circularly Doubly Linked list (Create, Display)
3.4 Generalized linked list – Concept and Representation
3.1 Introduction to Linked List
Linked list is a linear dynamic data structure. It is a
collection of some nodes containing homogeneous
elements.
Each node consists of a data part and one or more address
part depending upon the types of the linked list.
There three different types of linked list available which
are
1. Singly linked list
2. Doubly linked list
3. Circular linked list
Advantages of Linked Lists:
1) Facilitate Dynamic Memory Management:
The linked list is a collection of nodes and The array is a collection of similar types of data
1) each node is having one data field and next elements. In arrays the data is always stored at
data field. some index of array.
Any element can be accessed by sequential Any element can be accessed by randomly i.e.
2)
access only. with the help of index of array.
4) Insertion and deletion of data is easy. Insertion and deletion of data is easy.
Memory allocation is dynamic. Hence The memory allocation is static. Hence once the
developer can allocate as well as deallocate fixed amount of size is declared then that much
5)
the memory, so no wastage of memory is memory is allocated. So there is a chance of
there. memory wastage or memory shortage.
3.2 Implementation of linked List-Static and Dynamic
Representation
A) Static Representation:
The linked list is maintained by two linear arrays- one is used for data and the other for links. Let DATA
and LINK be the two arrays, DATA contains the information part, and their corresponding pointers to the
next node are stored in the array LINK.
B) Dynamic Representation:
In this representation, a memory bank that is a collection of free memory space and memory
manager program is used.
§ In above Figure , a new node is taken from the AVAIL and temporarily holds the address
§ The new node is then added to the existing list. The dotted arrow shows the insertion of the
new node to the list and the symbol is used to represent the deletion of links.
§ The head node in the list does not contain any data.
In above figure, deletions of the new node from the existing list are done and it is returned to the memory
bank i.e. AVAIL. The LINK field of the last node in the AVAIL will be pointing to the deleted node.
3.3 Types of Linked List
1. Singly Linked List
Singly linked list is a linked list which is a linear list of some nodes
containing homogeneous elements .
Each node in a singly linked list consists of two parts,
1. One is data part
The data part contains the data or information and except the last node.
2. Address part.
The address part contains the address of the next node in the list.
The address part of the last node in the list contains NULL.
Here one pointer is used to point the first node in the list.
Three basic operations on singly linked list which are
1. Insertion of a new node,
2. Deletion of a node
3. Traversing the linked list.
A) Operations on a Singly Linked List:
1) Creating a Singly Linked List:
A node of a linked list is a structure because it contains data of different types. In addition
to the
information part, it contains a pointer that can point to a node i.e. to itself or to some other
node
Node to be Appended
The node to be inserted must appear after the second node. Now; the next pointer of the
node 30 should be made point to node 40. The next pointer of the node, where temp is
currently positioned must be made to point, where pointer temp points. This is done by the
following two lines of code.
temp->next=locptr->next;
locptr->next = temp;
Temp points to the node 30 that is to be appended. This is shown in below Figure
§ Each node of the doubly linked list has two pointer fields and holds the address of predecessor and
successor elements.
§ These pointers enable bi-directional traversing, i.e. traversing the list in backward and forward
direction.
§ In several applications, it is very essential to traverse the list in backward direction. The pointer
pointing to the predecessor node is called left link and pointer pointing to successor is called right
link.
§ The pointer field of the first and last node holds NULL value, i.e. the beginning and end of the list
can be identified by NULL value. The structure of the node is as shown in Figure
3) Circularly Linked List:
A circular list is one in which the next field of the last node points to the first node of the list
or the next field of the last node contains the address of the first node of the list.
The two pointers front and rear can be used to associate with the first and last node
respectively.
B) Circularly Doubly Linked List:
A circularly double linked list is one in which the next field of last node points the first node and the previous field of the first node
points the last node.
For convenient traversal of the list and to simplify the insertion and deletion of nodes, a header node can be placed at the front of the list.
UNIT 4: Stack
4.1 Introduction
4.2 Representation of Stacks
4.3 Primitive Operations on Stacks
4.4 Applications of Stacks
4.5 Conversion of Infix, Prefix,Postfix
Evaluation of Postfix and Prefix
1.1 Introduction
What is Stack?
Stack is an ordered list of the same type of elements.
It is a linear list where all insertions and deletions are permitted only at one end of the list.
Stack is a LIFO (Last In First Out) structure.
In a stack, when an element is added, it goes to the top of the stack.
Definition
“Stack is a collection of similar data items in which both insertion and deletion operations are
performed based on LIFO principle”.
4. Isfull()
This operation checks whether the stack isfull. It returns TRUE if stack is full and false otherwise
Following table shows the Position of Top which indicates the status of stack
Position of Top Status of Stack
-1 Stack is empty.
0 Only one element in a stack.
N-1 Stack is full.
N Stack is overflow. (Overflow state)
4.4 Applications of Stack :
Following are some of the important applications of a Stack data structure:
1. Stacks can be used for expression evaluation.
2. Stacks can be used to check parenthesis matching /correctness of nested parenthesis.
3. Reversing a string.
4. Check whether string is palindrome or not.
5. Stacks can be used for Conversion from one form of expression to another.
A. Infix to Postfix or Infix to Prefix Conversion
The stack can be used to convert some infix expression into its postfix equivalent, or prefix
equivalent.
B. Postfix or Prefix Evaluation
These postfix or prefix notations are used in computers to express some expressions.
6. Stacks can be used for Memory Management.
7. Stack data structures are used in backtracking problems.
Backtracking can be defined as a general algorithmic technique that considers searching every possible
combination in order to solve a computational problem.
backtracking is, that is solving all sub-problems one by one in order to reach the best possible
solution.
Decision Problem – In this, we search for a feasible solution.
Optimization Problem – In this, we search for the best solution.
Enumeration Problem – In this, we find all feasible solutions.
Functions of Stack
Push() Pop() Display()
Postfix expression
ABC*DE/F-G*-H*+
Example : ( A + B ) * ( C - D )
The given infix expression can be converted into postfix expression using Stack data Structure as follows...
2. Infix to Prefix Conversion
Result
+*+A^BCD^E5
Example : 4,5,4,2,^,+,*,2,2,^,7,3,/,*,-
Step Symbol Operator in Stack
1 4 4
2 5 4,5
3 4 4.5.4
4 2 4,5,4,2
5 ^ 4,5,16
6 + 4,21
7 * 84
8 2 84,2
9 2 84,2,2
10 ^ 84,4
11 9 84,4,9
12 3 84,4,9,3
13 / 84,4,3
14 * 84,12
15 - 72
Que 1. Solve the following expression Que 2. Solve the following expression
5,6,2+,*,12,4,/,- 15,3,2+,5,/,3,7,+,10,2,*
Answer = 37 Answer
Answer ==20
37
efg-+he-sh-o+/* NULL
fg-+he-sh-o+/* “e”
g-+he-sh-o+/* “f”
3. Postfix to Infix “e”
Example: Convert Postfix to Infix efg-+he-sh-o+/* “g”
-+he-sh-o+/* “f”
“e”
+he-sh-o+/* “f”-“g”
“e”
he-sh-o+/* “e+f-g”
e-sh-o+/* “h”
“e+f-g”
-sh-o+/* “e”
“h”
“e+f-g”
sh-o+/* “h-e”
“e+f-g”
h-o+/* “s”
“h-e”
“e+f-g”
-o+/* “h”
“s”
“h-e”
“e+f-g”
o+/* “h-s”
“h-e”
“e+f-g”
“o”
+/* “s-h”
“h-e”
“e+f-g”
In the above diagram, Front and Rear of the queue point at the first index of the array. (Array
index starts from 0).
While adding an element into the queue, the Rear keeps on moving ahead and always points to
the position where the next element will be inserted. Front remains at the first index.
5.3 Primitive operation on a queue
The basic operation that can be perform on queue
are;
1. Insert an Element in a Queue.
2. Delete an Element from the Queue.
Front
Functions of Queue
insert() delete() display()
insert() delete() display()
{ { {
int add_item; if (front == - 1 || front > rear) int i;
if (rear == MAX - 1) { if (front == - 1)
{ printf("Queue Underflow \n"); {
printf("Queue Overflow \n"); } printf("Queue is empty \n");
} else }
else { else
{ printf("Deleted Element is : {
if (front == - 1) %d\n", queue_array[front]); for (i = front; i <= rear;
{ front = front + 1; i++)
front = 0; } {
} } printf("%d \n", queue_array[i]);
printf("Inset the element in queue : "); }
scanf("%d", &add_item); }
rear = rear + 1; }
queue_array[rear] = add_item;
}
}
Program of Queue using Array
#include <stdio.h> insert() display()
#define MAX 50 { {
int queue_array[MAX]; int add_item; int i;
int rear = - 1; if (rear == MAX - 1) if (front == - 1)
int front = - 1; { {
main() printf("Queue Overflow \n"); printf("Queue is empty \n");
{ } }
int choice; else else
while (1) { {
{ if (front == - 1) for (i = front; i <= rear; i++)
printf("1.Insert \n"); { {
printf("2.Delete\n"); front = 0; printf("%d ", queue_array[i]);
printf("3.Display \n"); } }}}
printf("4.Exit \n");
printf("Enter your choice : ");
printf("Inset the element in queue : ");
scanf("%d", &add_item);
1. Insert Element in Queue
scanf("%d", &choice); rear = rear + 1;
switch (choice) queue_array[rear] = add_item;
{ }
case 1: }
insert(); delete()
break; {
case 2: if (front == - 1 || front > rear)
delete(); {
break; printf("Queue Underflow \n");
case 3: }
display(); else 2. Display Element 3. Delete Element
break; {
case 4: printf("Deleted Element is : %d\n",
exit(1); queue_array[front]);
default: front = front + 1;
printf("Inavlid choice \n"); }
} }
}
}
Types of Queue in Data Structure
There are four types of Queue:
1. Linear Queue
2. Circular Queue
3. Priority Queue
4. Dequeue (Double Ended Queue)1. Simple Queue
1. Linear Queue
In this queue the elements are arranged into sequential manner. Such that front
position is always less than or equal to the rear position. When an element is added,
rear is incremented and when an element is removed front is advanced. Thus front
always rear
2. Circular Queue
•In this queue , the elements are arranged in a sequential manner but can logically be regarded as
circularly arranged.
•In a normal Queue Data Structure, we can insert elements until queue becomes full. But once the
queue becomes full, we can not insert the next element until all the elements are deleted from the
queue.
•For example, consider the queue below...The queue after inserting all the elements into it is as
follows...
Now consider the following situation after deleting three elements from the queue...
This situation also says that Queue is Full and we cannot insert the new element because 'rear' is
still at last position. In the above situation, even though we have empty positions in the queue we
can not make use of them to insert the new element. This is the major problem in a normal queue
data structure. To overcome this problem we use a circular queue data structure.
In a circular queue, all nodes are treated as circular. Last node is
connected back to the first node.
Circular queue is also called as Ring Buffer.
It is an abstract data type.
Circular queue contains a collection of data which allows insertion
of data at the end of the queue and deletion of data at the beginning
of the queue.
Double Ended Queue can be represented in TWO ways, those are as follows...
1. Input Restricted Double Ended Queue
2. Output Restricted Double Ended Queue
1. Input Restricted Double Ended Queue
In input restricted double-ended queue, the insertion operation is performed at only one end and deletion operation is
performed at both the ends.
2. Edge
In a tree data structure, the connecting link between any two nodes is called as EDGE. In a tree
with 'N' number of nodes there will be a maximum of 'N-1' number of edges.
3. Parent
In a tree data structure, the node which is a predecessor of any node is called as PARENT NODE. In
simple words, the node which has a branch from it to any other node is called a parent node. Parent
node can also be defined as "The node which has child / children".
4. Child
In a tree data structure, the node which is descendant of any node is called as CHILD Node. In simple
words, the node which has a link from its parent node is called as child node. In a tree, any parent node
can have any number of child nodes. In a tree, all the nodes except root are child nodes.
5. Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple words,
the nodes with the same parent are called Sibling nodes.
6. Leaf
In a tree data structure, the node which does not have a child is called as LEAF Node. In simple words,
a leaf is a node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes. External node is also a node
with no child. In a tree, leaf node is also called as 'Terminal' node.
7. Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In simple
words, an internal node is a node with atleast one child.
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root node is
also said to be Internal Node if the tree has more than one node. Internal nodes are also called as
'Non-Terminal' nodes.
8. Degree
In a tree data structure, the total number of children of a node is called as DEGREE of that Node. In
simple words, the Degree of a node is total number of children it has. The highest degree of a node
among all the nodes in a tree is called as 'Degree of Tree'
9. Level
In a tree data structure, the root node is said to be at Level 0 and the children of root node are at
Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so on... In simple
words, in a tree each step from top to bottom is called as a Level and the Level count starts with '0'
and incremented by one at each level (Step).
10. Height
In a tree data structure, the total number of edges from leaf node to a particular node in the longest
path is called as HEIGHT of that Node. In a tree, height of the root node is said to be height of the
tree. In a tree, height of all leaf nodes is '0'.
11. Depth
In a tree data structure, the total number of egdes from root node to a particular node is called
as DEPTH of that Node. In a tree, the total number of edges from root node to a leaf node in the
longest path is said to be Depth of the tree. In simple words, the highest depth of any leaf node in a
tree is said to be depth of that tree. In a tree, depth of the root node is '0'.
12. Path
In a tree data structure, the sequence of Nodes and Edges from one node to another node is called
as PATH between that two Nodes. Length of a Path is total number of nodes in that path. In below
example the path A - B - E - J has length 4.
In a left skewed tree, most of the nodes have the left child
without corresponding right child.
In a right skewed tree, most of the nodes have the right child
without corresponding left child.
6.3 Binary Tree Representations
A binary tree data structure is represented using two methods. Those methods are as follows...
1. Array Representation
2. Linked List Representation
Consider the following binary tree...
The above example of the binary tree represented using Linked list representation is shown as follows..
Binary Search Tree
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.
Each node has following attributes:
I. Parent (P), left, right which are pointers to the parent (P), left child and right child respectively.
II. Key defines a key which is stored at the node.
Definition:
"Binary Search Tree is a binary tree where each node contains only smaller values in its left subtree
and only larger values in its right subtree."
1. Preorder Traversal(NLR)
Algorithm for preorder traversal
Step 1 : Start from the Root.
Step 2 : Then, go to the Left Subtree.
Step 3 : Then, go to the Right Subtree.
Step 1 : A + B (B + Preorder on D (D + Preorder on E and F)) + C (C + Preorder on G and
H)
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
2. Postorder Traversal(LRN)
Algorithm for postorder traversal :
Step 1 : Start from the Left Subtree (Last Leaf).
Step 2 : Then, go to the Right Subtree.
Step 3 : Then, go to the Root.
3. Inorder Traversal
Algorithm for inorder
traversal
Step 1 : Start from the Left Subtree.
Step 2 : Then, visit the Root.
Step 3 : Then, go to the Right Subtree.
6.7 AVL Tree
Balance Factor
Height of Node
Balance Factor
AVL Rotations
To balance itself, an AVL tree may perform the following
four kinds of rotations −
1. Left rotation
2. Right rotation
3. Left-Right rotation
4. Right-Left rotation
The first two rotations are single rotations and the next two
rotations are double rotations.
1. Left Rotation
If a tree becomes unbalanced, when a node is inserted into
the right subtree of the right subtree, then we perform a
single left rotation −
1. Directed Graph :
A graph with only directed edges is called
directed graph.
2. Undirected Graph :
A graph without direction is called undirected
graph.
In which each edge is not assigned a direction.
3. Connected Graph
A graph G is said to be connected if there
exists a path between every pair of
vertices. There should be at least one edge
for every vertex in the graph. So that we can
say that it is connected to some other vertex
at the other side of the edge.
4. Disconnected Graph :
A graph G is disconnected,
if it does not contain at least two connected
vertices.
The following graph is an example of a
Disconnected Graph, where there are two
components, one with ‘a’, ‘b’, ‘c’ vertices and
another with ‘e’, ’f’, ‘g’vertices.
The two components are independent and not
connected to each other. Hence it is called
disconnected graph.
5. Mixed Type Graph
A graph in which some edges are directed
and some edges are undirected such a graph
is called as mixed type graph.
6. Cyclic Graph :
A graph with at least one cycle is called a
cyclic graph.
7. Acyclic Graph :
A graph with no cycle is called Acyclic graph.
8. Weighted Graph :
In a weighted graph, each edge has an associated
numerical value, called the weight of the edge
Edge weights may represent distance, time, cost, etc.
A weighted graph can be directed or undirected.
Graph - Terminology
1. Vertex
Individual data element of a graph is called as
Vertex. Vertex is also known as node.
In above example graph, A, B, C, D & E are
known as vertices.
2. Edge
An edge is a connecting link between two
vertices.
Edge is also known as Arc.
3. Path
A path is a sequence of alternate vertices and edges
that starts at a vertex and ends at other vertex such
that each edge is incident to its predecessor and
successor vertex.
Graph - Terminology
4. Adjacent node
Vertices B and E are said to be adjacent node .
If there is an edge between vertices B and E
5. Outgoing Edge
A directed edge is said to be outgoing edge on its
origin vertex.
6. Incoming Edge
A directed edge is said to be incoming edge on its
destination vertex.
7. Degree
Total number of edges connected to a
vertex is said to be degree of that vertex.
8. In degree
Total number of incoming edges
connected to a vertex is said to be in
degree of that vertex.
9. Out degree
Total number of outgoing edges connected
to a vertex is said to be out degree of that
vertex.
Graph - Terminology
10. Source
A node which has only out going edges and no
incoming edges is called source
11. Sink
A node which has only incoming edges and no
outgoing edges is called sink
1. Adjacency Matrix
In this representation, the graph is represented using a matrix of size total number of vertices.
That means a graph with 4 vertices is represented using a matrix of size 4X4.
In this matrix, both rows and columns represent vertices.
This matrix is filled with either 1 or 0. Here, 1 represents that there is an edge from row vertex to
column vertex and 0 represents that there is no edge from row vertex to column vertex.
Degree of Nodes
A=3
B=3
C=2
D=5
E=2
Directed graph representation...
InDegree OutDegree
of Nodes of Nodes
A=1 A=2
B=1 B=2
C=1 C=1
D=3 D=3
E=2 E=0
2. Adjacency List
In this representation, every vertex of a graph contains list of its adjacent vertices.
For example, consider the following directed graph representation implemented using linked list...
Example : Graph data structure is represented using following representations...
1. Adjacency Matrix 2. Adjacency List
Example : Graph data structure is represented using following representations...
1. Adjacency Matrix 2. Adjacency List
As in the example given above, DFS algorithm traverses from S to A to D to G to E to B first, then
to F and lastly to C. It employs the following rules.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the
vertices from the stack, which do not have adjacent vertices.)
Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
Step Traversal Description
As C does not have any unvisited adjacent node so we keep popping the stack until we find a node
that has an unvisited adjacent node. In this case, there's none and we keep popping until the stack is
empty DFS Traversing = S,A,D,C
1 2
5 6
Solve Example DFS
DFS Traversing = 3 4
Step Traversal Description
7
DFS Traversal = A B C D E F
Example of the DFS algorithm
Step Traversal Description
13 DONE
(The stack hasbecome empty)
Traversal order
14