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

Dsa Material QB QP

This document provides an overview of key concepts related to data structures and algorithms, including: 1) Data structures organize data in a logical way and allow specific operations on that data. Common linear structures are arrays, linked lists, stacks, and queues, while nonlinear structures include trees and graphs. 2) Algorithms use a series of well-defined steps to solve problems in a finite number of ways. They must be unambiguous and able to terminate. 3) Common operations on data structures include traversing, searching, inserting, deleting, sorting, and merging data items. 4) Abstract data types define behavior without specifying implementation, hiding representation details.

Uploaded by

yanele6282
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Dsa Material QB QP

This document provides an overview of key concepts related to data structures and algorithms, including: 1) Data structures organize data in a logical way and allow specific operations on that data. Common linear structures are arrays, linked lists, stacks, and queues, while nonlinear structures include trees and graphs. 2) Algorithms use a series of well-defined steps to solve problems in a finite number of ways. They must be unambiguous and able to terminate. 3) Common operations on data structures include traversing, searching, inserting, deleting, sorting, and merging data items. 4) Abstract data types define behavior without specifying implementation, hiding representation details.

Uploaded by

yanele6282
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

Ananthasagar village, Hasanparthy Mandal, Hanmakonda District – 500 376

DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLEGENCE

Data Structures and Algorithms


(Study Material for all units, Question Bank & Previous Year Question Paper)

By
Mr. Radhakrishnan.P, M.Tech,M.C.A,M.B.A(HR),M.Sc(Psy),B.Lit(Tamil), M.A(Criminology),(Ph.D).
Assistant Professor
School of CS & AI
SR University
SYLLABUS
DATA STRUCTURES AND ALGORITHMS
UNIT I
Basic concepts - Data types, Abstract Data Types, Data structures, Algorithms.
Searching- Linear Search, Binary Search
Sorting- Bubble Sort, Insertion Sort, Selection Sort, Quick sort, Merge sort, Comparison of Sorting methods.

UNIT II
Linear Data Structures Part 1:
Stack ADT - Definitions, operations, array and linked implementations, applications-infix to postfix conversion,
recursion implementation,
Queue ADT - Definitions and operations, array and linked Implementations, Applications of Queue Circular queues
and operations

UNIT III
Linear Data Structures Part 2:
Linear Lists, Sequential and Linked allocation, list ADT, array and linked Implementations, Singly Linked Lists-
Operations-Insertion, Deletion, Doubly Linked Lists-Operations - Insertion, Deletion.

UNIT IV
Non Linear Data Structures Part 1:Trees - Basic Terminology, Binary tree ADT, array and linked
representations, traversals, threaded binary trees, Priority Queues-Definition, ADT, Realizing a Priority Queue using
Heap.
Search Trees: Binary Search Trees, Definition, ADT, Implementation, Operations- Searching, Insertion and
Deletion.
Balanced Search Trees: AVL Trees - Definition, Operations – Insertion and Searching.
B-Trees - Definition, B-Tree of order m, operations - insertion and deletion. Introduction to Red-Black and Splay
Trees, Comparison of Search Trees.

UNIT V

Non Linear Data Structures Part 2:


Graphs – Introduction, Basic Terminology, Graph Representations- Adjacency matrix, Adjacency lists, Adjacency
multilists, Graph traversals- DFS and BFS, Disjoint Sets, Union and Find algorithms, Spanning Trees – kruskals,
prims algorithms.

TEXT BOOKS:
rd
1. Mark Allen Weiss, “Data structures and Algorithm Analysis”, 3 edition, Pearson Education. Ltd.,
2. S.Sahani, “Data structures, Algorithms and Applications”, Universities Press.

REFERENCE BOOKS:
1. Michael T.Goodrich, R.Tamassia and D.Mount, “Data structures and Algorithms”, Wiley student edition,
seventh edition, John Wiley and Sons.
2. Adam Drozdek, “Data structures and algorithms”, 3rd Edition, Cengage Learning.
3. Langsam, Augenstein and Tanenbaum, “Data structures using C”, PHI.
4. G.L.Heileman, “Data structures, algorithms and OOP”, TMH edition
Unit - 1 Data Structures and Algorithms

UNIT I
Basic concepts - Data types, Abstract Data Types, Data structures, Algorithms.
Searching- Linear Search, Binary Search
Sorting- Bubble Sort, Insertion Sort, Selection Sort, Quick sort, Merge sort, Comparison of
Sorting methods.

Data Structures
 Data may be organized in many different ways logical or mathematical model of a program
particularly organization of data. This organized data is called “Data Structure”.
 Or
 The organized collection of data is called a ‘Data Structure’.

Data Structure=Organized data +Allowed operations

Data Structure involves two complementary goals.


1. The first goal is to identify and develop useful, mathematical entities and operations
and to determine what class of problems can be solved by using these entities and
operations.
2. The second goal is to determine representation for those abstract entities to
implement abstract operations on this concrete representation.

Data Types
 Primitive Data types are directly supported by the language (ie) any operation is directly
performed in these data items.
o Ex: integer, Character, Real numbers etc.

 Non-primitive data types are not defined by the programming language, but are instead
created by the programmer.
1. Linear data structures organize their data elements in a linear fashion, where data
elements are attached one after the other. Linear data structures are very easy to
implement, since the memory of the computer is also organized in a linear fashion.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Some commonly used linear data structures are arrays, linked lists, stacks and
queues.
2. In nonlinear data structures, data elements are not organized in a sequential fashion.
Data structures like multidimensional arrays, trees, graphs, tables and sets are some
examples of widely used nonlinear data structures.

Operations on the Data Structures:


Following operations can be performed on the data structures:
1. Traversing- It is used to access each data item exactly once so that it can be processed.
2. Searching- It is used to find out the location of the data item if it exists in the given
collection of data items.
3. Inserting- It is used to add a new data item in the given collection of data items.
4. Deleting- It is used to delete an existing data item from the given collection of data items.
5. Sorting- It is used to arrange the data items in some order i.e. in ascending or descending
order in case of numerical data and in dictionary order in case of alphanumeric data.
6. Merging- It is used to combine the data items of two sorted files into single file in the sorted
form.

Abstract Data Type


 In computer science, an abstract data type (ADT) is a mathematical model for data
types where a data type is defined by its behavior (semantics) from the point of view
of a user of the data, specifically in terms of possible values, possible operations on
data of this type, and the behavior of these operations.
 When a class is used as a type, it is an abstract type that refers to a hidden
representation. In this model an ADT is typically implemented as a class, and each
instance of the ADT is usually an object of that class.
 In ADT all the implementation details are hidden.

Algorithm
Definition: -
An algorithm is a Step By Step process to solve a problem, where each step indicates an
intermediate task. Algorithm contains finite number of steps that leads to the solution of the
problem.

Properties /Characteristics of an Algorithm:-


Algorithm has the following basic properties
 Input-Output:- Algorithm takes ‘0’ or more input and produces the required output.
This is the basic characteristic of an algorithm.
 Finiteness:- An algorithm must terminate in countable number of steps.
 Definiteness: Each step of an algorithm must be stated clearly and unambiguously.
 Effectiveness: Each and every step in an algorithm can be converted in to programming
language statement.
 Generality: Algorithm is generalized one. It works on all set of inputs and provides the
required output. In other words it is not restricted to a single input value.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Categories of Algorithm:
Based on the different types of steps in an Algorithm, it can be divided into three categories,
namely
 Sequence
 Selection and
 Iteration

Sequence:
 The steps described in an algorithm are performed successively one by one without
skipping any step.
 The sequence of steps defined in an algorithm should be simple and easy to understand.
 Each instruction of such an algorithm is executed, because no selection procedure or
conditional branching exists in a sequence algorithm.
Example:
// adding two numbers
Step 1: start
Step 2: read a,b
Step 3: Sum=a+b
Step 4: write Sum
Step 5: stop

Selection:
 The sequence type of algorithms are not sufficient to solve the problems, which involves decision
and conditions. In order to solve the problem which involve decision making or option selection,
we go for Selection type of algorithm.
 The general format of Selection type of statement is as shown below:
if(condition)
Statement-1;
else
Statement-2;

 The above syntax specifies that if the condition is true, statement-1 will be executed otherwise
statement-2 will be executed. In case the operation is unsuccessful.
 Then sequence of algorithm should be changed/ corrected in such a way that the system will re-
execute until the operation is successful.

 Iteration: Iteration type algorithms are used in solving the problems which involves
repetition of statement.
 In this type of algorithms, a particular number of statements are repeated ‘n’ no. of times.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat
step 4 : until n>0
(a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop

Performance Analysis an Algorithm:


The Efficiency of an Algorithm can be measured by the following metrics.
i. Time Complexity:
 The amount of time required for an algorithm to complete its execution is its time
complexity.
 An algorithm is said to be efficient if it takes the minimum (reasonable) amount
of time to complete its execution.
ii. Space Complexity:
 The amount of space occupied by an algorithm is known as Space Complexity.
 An algorithm is said to be efficient if it occupies less space and required the
minimum amount of time to complete its execution.
**************
Searching
• Searching is a process of finding a particular element among several given elements.
• The search is successful if the required element is found.
• Otherwise, the search is unsuccessful.
Searching Algorithms-
The searching of an element in the given array may be carried out in the following two ways-

1.Linear Search
• Linear search, the simplest search algorithm, is mainly used to find the element from
an unordered list.
• It is also known by another name called sequential search algorithm. In linear search,
the list is simply traversed, and each element in the list is matched with the element whose
location needs to be found.
• When the searching process is done, it returns the location of the element, else the
algorithm returns NULL.

Ex: consider the following Array A


23 15 18 17 42 96 103
 Now let us search for 17 by Linear search. The searching starts from the first
position. Since A[0] ≠17.
 The search proceeds to the next position i.e; second position A[1] ≠17.
 The above process continuous until the search element is found such as A[3]=17. Here
the searching element is found in the position 4.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C implementation for Linear Search


#include <stdio.h>
int main()
{
int i,size,a[10],search,flag=0;
printf("\n Enter the size of an array :");
scanf("%d",&size);
printf("\n Enter the value :");
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("\n Find the search element : ");
scanf("%d",&search);

for(i=0;i<size;i++)
{
if(search==a[i])
{
flag=1;
break;
}
}
if (flag==1)
printf("%d fount at the position %d ",search,mid+1);
else
printf("element not found");
return 0;
}
Advantages:
It is simplest known technique.
The elements in the list can be in any order.
Disadvantages:
This method is in efficient when large numbers of elements are present in list because time
taken for searching is more.
Complexity of Linear Search: The worst and average case complexity of Linear search is
O(n), where ‘n’ is the total number of elements present in the list.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Binary Search
 Binary Search is one of the fastest searching algorithms.
 It is used for finding the location of an element in a linear array.
 It works on the principle of divide and conquer technique.
 Binary Search Algorithm can be applied only on Sorted arrays.(Ascending Order)
 So, the elements must be arranged in Either ascending order if the elements are numbers Or
dictionary order if the elements are strings.
 To apply binary search on an unsorted array,First, sort the array using some sorting
technique.Then, use binary search algorithm.

Binary Search Algorithm-


Hints:
 There is a linear array ‘a’ of size ‘n’.(sorted order)
 Find mid =(start+stop)/2
 Case 1 : Search==a[mid] then element found
 Case 2 : Search < a[mid] . Stop = mid-1
 Case 3 : Search > a[mid]  Start = mid +1

C CODE FOR BINARY SEARCH:


#include <stdio.h>
int main()
{
int i,size,a[10],search,start,mid,stop,flag=0;
printf("\n Enter the size of an array :");
scanf("%d",&size);

printf("\n Enter the value (ascending order) :");


for(i=0;i<size;i++)
scanf("%d",&a[i]);

printf("\n Find the search element : ");


scanf("%d",&search);

start=0;
stop=size-1;

while(start<=stop)
{
mid=(start+stop)/2;
if(search==a[mid])
{
flag=1;
break;
}
else if (search<a[mid])
stop=mid-1;
else
start=mid+1;
}
if(flag==1)
printf("%d fount at the position %d ",search,mid+1);
else
printf("element not found");
return 0;
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

The advantages of binary search algorithm are-


 It is a much faster algorithm.
 It works on divide and conquers principle.
 It eliminates half of the list from further searching by using the result of each comparison.
The disadvantages of binary search algorithm are-
 It can be used only when data is sorted.
 It is more complicated.
 Random access is not supported.
Example:

Time Complexity Analysis-


Best case : O(1)
Worst Case and average case : O(log n).
***********
SORTING
A sorting algorithm is used to arrange elements of an array/list in a specific order.

Types of Sorting
1.Bubble Sort
2.Selection Sort
3.Insertion Sort
4.Merge Sort
5.Quick Sort

1.BUBBLE SORT
 Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until
they are in the intended order.
 Just like the movement of air bubbles in the water that rise up to the surface, each element of
the array move to the end in each iteration.
 Therefore, it is called a bubble sort.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Algorithm :
Step 0 : Initialize n to length of the array
Step 1 : Initialize j to 0 and compare a[j] with a[j+1] (compare adjacent elements starting
from 0th index)
Step 2 : if a[j] > a[j+1] swap a[j] and a[j+1]
Step 3 : repeat steps 1 and 2 until j reached end of the array ( by end of this one element will
be placed at its correct order )
Step 4 : continue from Step 1 n-1 times ( so that all elements will be in proper order)

Example:

C CODE FOR BUBBLE SORT :


#include <stdio.h>
int main()
{
int a[50],n,i,j,temp;

printf("Enter Size of an Array :");


scanf("%d",&n);

printf("Values are");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Ascending Order Using Bubble Sort \n");
for(i=0;i<n;i++)
printf("\t %d",a[i]);
return 0;
}

OUTPUT

Enter Size of an Array :8


Values are
25 57 48 37 12 92 86 33
Ascending Order Using Bubble Sort 12 25 33 37 48 57 86 92
*********
2.SELECTION SORT
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from the unsorted part and putting it at the beginning.
Algorithm :
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.
Example

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C CODE FOR SELECTION SORT :


#include <stdio.h>
int main()
{
int a[100], n, i, j, min,temp;

printf("Enter number of elements \n");


scanf("%d", &n);

printf("Enter Values");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);

for(i = 0; i < n - 1; i++)


{
min=i;
for(j = i + 1; j < n; j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
printf("Sorted Array:\n");
for(i = 0; i < n; i++)
printf("%d \n", a[i]);
return 0;
}
OUTPUT
Enter number of elements
5
Enter Values 77 -1 64 234 14
Sorted Array:
-1 14 64 77 234
************

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

INSERTION SORT
 Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in
each iteration.
 Insertion sort is a simple sorting algorithm that works similar to the way you sort playing
cards in your hands
Advantage
o Simple implementation
o Efficient for small data sets
o Adaptive, i.e., it is appropriate for data sets that are already substantially sorted.
Algorithm
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step 2 - Pick the next element, and store it separately in a key.
Step 3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
EXAMPLE :

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C CODE FOR INSERTION:


#include <stdio.h>
int main()
{
int a[100], n, i, j, temp;

printf("\n Enter the total Number of Elements : ");


scanf("%d", &n);

printf("\n Enter the Array Elements : ");


for(i = 0; i < n; i++)
scanf("%d", &a[i]);

for(i = 1; i <= n - 1; i++)


{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
printf("\n Insertion Sort Result : ");
for(i = 0; i < n; i++)
printf(" %d \t", a[i]);

return 0;
}

OUTPUT
Enter the total Number of Elements : 5
Enter the Array Elements : 25
6
97
-1
15
Insertion Sort Result : -1 6 15 25 97
***********
MERGE SORT
 Merge Sort is one of the most popular sorting algorithms that is based on the principle
of Divide and Conquer Algorithm.
 Here, a problem is divided into multiple sub-problems.
 Each sub-problem is solved individually.
 Finally, sub-problems are combined to form the final solution.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Divide and Conquer Strategy


 Using the Divide and Conquer technique, we divide a problem into sub problems.
 When the solution to each sub problem is ready, we 'combine' the results from the sub
problems to solve the main problem.

Algorithm:
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
Follow the steps below the solve the problem:
MergeSort(arr[], l, r)
If r > l
Find the middle point to divide the array into two halves:
middle m = l + (r – l)/2
Call mergeSort for first half:
Call mergeSort(arr, l, m)
Call mergeSort for second half:
Call mergeSort(arr, m + 1, r)
Merge the two halves sorted in steps 2 and 3:

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Call merge(arr, l, m, r)

C CODE FOR MERGE SORT:


#include<stdio.h>

void partition(int a[ ],int low,int high);


void merge(int a[],int low,int mid, int high);

int main()
{
int a[50],i,j,size,temp,low,high,mid,mi,k;

printf("Enter size of the array: ");


scanf("%d",&size);

printf("Enter array elements: ");


for(i=0;i<size;i++)
scanf("%d",&a[i]);

partition(a,0,size-1);

printf("\n Sorted array is: ");


for(i=0;i<size;i++)
printf("%d\t",a[i]);

return 0;
}

void partition(int a[],int low,int high)


{
int mid;
if(low<high)
{
mid=(low+high)/2;
partition(a,low,mid);
partition(a,mid+1,high);
merge(a,low,mid,high);
}
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

void merge(int a[],int low,int mid, int high)


{
int lower=low;
int i=low;
int mi=mid+1;
int temp[100],k;

while(lower<=mid&&mi<=high)
{
if(a[lower]<=a[mi])
{
temp[i]=a[lower];
lower++;
}
else
{
temp[i]=a[mi];
mi++;
}
i++;
}
if(lower>mid)
{
for(k=mi;k<=high;k++)
{
temp[i]=a[k];
i++;
}
}
else
{
for(k=lower;k<=mid;k++)
{
temp[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}

OUTPUT :

Enter size of the array: 6

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Enter array elements: 56 -1 15 98 4 69


Sorted array is: -1 4 15 56 69 98
QUICK SORT
1. An array is divided into subarrays by selecting a pivot element (element selected from the
array).
2. While dividing the array, the pivot element should be positioned in such a way that elements
less than pivot are kept on the left side and elements greater than pivot are on the right side
of the pivot.
3. The left and right subarrays are also divided using the same approach. This process
continues until each subarray contains a single element.
4. At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.

EXAMPLE

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C CODE FOR QUICK SORT :


#include<stdio.h>
void quicksort(int a[25],int first,int last)
{
int i, j, pivot, temp;

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot] && i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
int main()
{
int i, n, a[25];

printf("Enter the total Number of Elements : ");


scanf("%d",&n);

printf("Enter elements: ");


for(i=0;i<n;i++)
scanf("%d",&a[i]);

quicksort(a,0,n-1);

printf("Order of Sorted elements: ");


for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}

OUTPUT
Enter the total Number of Elements : 5
Enter elements: 12 5 47 11 1
Order of Sorted elements: 1 5 11 12 47

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Comparison of Sorting

**************

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

UNIT II
Linear Data Structures Part 1:
Stack ADT - Definitions, operations, array and linked implementations, applications-infix to
postfix conversion, recursion implementation,
Queue ADT - Definitions and operations, array and linked Implementations, Applications of
Queue Circular queues and operations

Stack
 Stack is a linear DS.
 LIFO or FILO
Insertion and deletion can be done at only one end of the stack called top of the stack.
Top position :-
 It is always point to the last element inserted in the stack.
 For empty stack , top position value is -1.

Application of stack:

Operation
1. PUSH
2. POP
3. PEEK

Stack Using Array Implementation


#define SIZE 5
int stack[SIZE], top = -1;

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

1.push () operation
int push(int value)
{
if(top == SIZE-1)
printf("\nStack is Full");
else
{
top++;
stack[top] = value;
printf("\nInsertion success");
}
}
2.Pop() operation
int pop()
{
if(top == -1)
printf("\nStack is Underflow");
else
{
printf("\nDeleted : %d", stack[top]);
top--;
}
}
3.Peek() operation
int peek()
{
if(top == -1)
printf("\nStack is Underflow");
else
printf("\n Peek of Stack : %d", stack[top]);
}
4.Traverse
int display()
{
if(top == -1)
printf("\nStack is Underflow");
else
{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

INFIX TO POSTFIX CONVERSION


Arithmetic Expression have:
 Operands (variables or numeric
constants).
 Operators :- + , - , * , /, %,^
 Priority
^ (High priority)
*,/,% (Medium priority)
+,- (Low priority)
Infix ,Prefix and postfix
Example : Arithmetic expression a+b consists of operands a,b and operator +.
Infix Notation (between)
Is format where operator is specified in between the two operands. ( a + b)
Prefix Notation (before)
Is format where operator is specified in before the two operands. ( + a b)
Postfix Notation (after)
Is format where operator is specified in after the two operands. ( a b - )
Converting Arithmetic Expressions
Example : Conversion from infix arithmetic expression to prefix notation

Conversion from Infix to Postfix Algorithm


1. Scan the infix expression from left to right for tokens(operators,operands & parentheses)
and perform the steps 2 to 5 for each token in the expression.
2. If token is operand, append it in postfix expression.
3. If token is a left parentheses “(“, push it in stack.
4. If token is an operator.
 Pop all the operators which are of higher or equal precedence then the incoming
token and append them(in the same order) to the output expression.
 After popping out all such operators, push the new token on stack.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

5. If “)” right parentheses is found.


 Pop all the operators from the stack and append them to output string, till you
encounter the opening parenthesis “(“
 Pop the left parenthesis but don’t append it to the output string (Postfix notation
does not have brackets).
6. When all tokens of Infix expression have been scanned. Pop all the elements from the
stack and append them to the output string.
 The output string is the corresponding Postfix Notation.
Example 1:
Infix notation => A - B

Example 2:
Infix notation => A + B - C

Example 3:
Infix notation => A + B * C

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

Parentheses in Infix Notation


How are parentheses handled when converting an Infix notation to postfix notation ?
 When a left parentheses “(“ is found in the infix string, it is immediately pushed
onto the operatorsStack object but its precendence is defined to be lower than any
other binary operator.
 When a right parentheses “)” is found in the infix string, the operator object is
repeatedly popped, and the popped element appended to the postfix string, Until
the operator on the top of the operatorStack object is the left paretheses “(“.
 Then the left parentheses “(“ is popped but not appended to the postfix string and
the scan of the infix string is continued.
Example:
Parentheses in Infix notation
Convert this infix notation to postfix notation
x–(y*a/b–(z + d * e) + c ) / f

-----------------------------------------
QUEUE
Queues are first-in-first-out (FIFO) structures – The first element added to a queue is the
first to be removed and the last element to be added to a queue will be the last to be
removed.

Ex : 1. Waiting line in the ticket counter. 2. Printing a document 3. Client-Server


Communication.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

Operation
1. Enqueue (Insertion ) – rear end
2. Dequeue(Deletion) – front end

Queue Using Array Implementation

#define SIZE 5
int queue[SIZE],front=0,rear=0,i;

1.enqueue operation
int enqueue()
{
if(rear==SIZE)
printf("\n Queue is Full");
else
{
printf("\n Enter number:");
scanf("%d",&queue[rear++]);
}
}
2.dequeue operation
int dequeue()
{
if(front==rear)
printf("\n Queue is empty");
else
printf("\n Deleted Element is %d",queue[front++]);
}
3.Traverse
int display()
{
if(front==rear)
printf("\n Queue is Empty");
else

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

{
printf("\n Queue Elements are:\n ");
for(i=front; i<rear; i++)
printf("%d \t",queue[i]);
}
}
-----------------------------------------
Circular Queue Using Array Implementation

 In a Linear queue, once the queue is completely full, it's not possible to insert any
more elements. When we dequeue any element to remove it from the queue, we are
actually moving the front of the queue forward, but rear is still pointing to the last
element of the queue, we cannot insert new elements.
 Circular Queue is also a linear data structure, which follows the principle of
FIFO(First In First Out), but instead of ending the queue at the last position, it again
starts from the first position after the last, hence making the queue behave like a
circular data structure.

Operations on Circular Queue:


The following are the operations that can be performed
1. enQueue(value): This function is used to insert the new value in the Queue. The new
element is always inserted from the rear end.
2. deQueue(): This function deletes an element from the Queue. The deletion in a Queue
always takes place from the front end.

1) Enqueue () Opeartion :
void enqueue()
{
int elt;

if( ((rear+1)%SIZE)==front)
{
printf("\n Circular Queue is full… insertion not possible...");
return;
}

//to add new elt


if(front==-1 && rear==-1)
front=rear=0;
else
rear=(rear+1)%SIZE;

printf("\n Enter the element :");


scanf("%d",&elt);

cqueue[rear]=elt;

printf("\n Insertion Successful");


}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

2 ) Dequeue operation
void dequeue()
{
if(front==-1 && rear==-1)
{
printf("\n Circular Queue is empty...");
return;
}
printf("Deleted Element is : %d",cqueue[front]);
if(front==rear)
front=rear=-1;
else
front=(front+1)%SIZE;
}

3) Traverse Or Display Operation


void display()
{
int c;
if(front==-1 && rear==-1)
{
printf("\nQueue is empty");
return;
}
c=(((rear+SIZE)-front)%SIZE)+1;

printf("\n Circular Queue Elements are:\n ");


for (i = 0; i <c; i++)
{
printf("%d \t ", cqueue[(front+i)%SIZE]);
}
}

Applications of Queue:
1. Queues are widely used as waiting lists for a single shared resource like printer, disk,
CPU.
2. Queues are used as buffers on MP3 players and portable CD players, iPod playlist.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

Example :

------------------------------------
Recursion
A function that calls itself is known as a recursive function.

Types of recursion in C
There are two types of recursion present in the C programming language.
 Direct Recursion
 Indirect Recursion

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

1. Direct Recursion in C
If a function calls itself directly then the function is known as direct recursive function.
Example:
int fib(int num)
{
if (num==1 || num==2)
return 1;
else
return (fib(num-1)+fib(num-2));
}
In the above example, fib() function is direct recursive. Because the statements inside the
fib() function calls the fib() function directly.

2. Indirect Recursion in C
A function that does not call itself directly then function is known as an indirect recursive
function.
Example
int first_function(int num)
{
if (num<=2)
return 2;
else
return new_function(num);
}
int new_function(int num)
{
return first_function(num);
}
In the above example, first_function() calls the new_function(), which is indeed a new
function. Then this new_function() calls the first_function(). So, it is an indirect recursive
function.
EXAMPLE:
Tower of Hanoi
 These rings are of different sizes and stacked upon in an ascending order, i.e. the
smaller one sits over the larger one.
 It is a mathematical game or puzzle that consists of three rods with ’n’ number of
disks of different diameters.
 The objective of the game is to shift the entire stack of disks from one rod to another
rod following these three rules :
1. Only one disk can be moved at a time.
2. Only the uppermost disk from one stack can be moved on to the top of
another stack or an empty rod.
3. Larger disks cannot be placed on the top of smaller disks.

The minimal number of moves required to solve the Tower of Hanoi puzzle of n disks would be (2^n) − 1.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

The steps to follow are −


Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

A recursive algorithm for Tower of Hanoi can be driven as follows −

START

Procedure Hanoi(disk, source, dest, aux)

IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

****************
Linked Representation of Stacks:
 The drawback in that the array must be declared to have some fixed size. In case the
stack is a very small one or its maximum size is known in advance
 In
 a linked stack, every node has two parts, one that stores data and another that stores
the address of the next node. The START pointer of the linked list is used as TOP.
 All insertions and deletions are done at the TOP (similar to insertion at beginning).
If TOP = NULL, then it indicates that the stack is empty.

Linked Implementation of Stack:


 In a linked stack, each node of the stack consists of two parts i.e. data part and the
next part. Each element of the stack points to its immediate next element in the
memory.
 In the linked stack, there one pointer maintained in the memory i.e. TOP pointer.
The TOP pointer contains the address of the starting element of the STACK.
 Both Insertion and deletions are performed at only one end called TOP. If TOP is
NULL, it indicates that the stack is empty. Initially
struct node *TOP = NULL ;

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

Applications of Stacks
✔ Stack is used to reversing the given string.
✔ Stack is used to evaluate a postfix expression.
✔ Stack is used to convert an infix expression into postfix/prefix form.
✔ Stack is used to matching the parentheses in an expression.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

1. Push Function
void push(int elt)
{
struct node *n;
n=(struct node*)malloc(sizeof(struct node));
n->data=elt;
n->next=top;
top=n;
printf("\n Insertion is sucessful");
}

2. Pop Function
void pop()
{
struct node *temp;
temp=top;
if(top==NULL)
printf("Stack Underflow");
else
{
printf("Pop out element is %d",top->data);
top=top->next;
free(temp);
}
}

3. Peek Function
void peek()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Top of the Stack %d ", top->data);
}

4. Traverse Or Display Function


void display()
{
struct node *temp;
temp=top;
if(top==NULL)
printf("Stack Underflow");
else
{

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

while(temp!=NULL)
{
printf("\t %d",temp->data);
temp=temp->next;
}
}
}
------------------------------------------
Queue Linked List Representation

ARRAYs: Queues can be easily represented using linear arrays. Every queue has front and
rear variables that point to the position from where deletions and insertions can be done,
respectively. The array representation of a queue is shown below.

Drawback: The array must be declared to have some fixed size. If we allocate space for 50
elements in the queue and it hardly uses 20–25 locations, then half of the space will be
wasted.

Array Representation:

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

Drawback: If we implement the queue using an array, we need to specify the array size
at the beginning (at compile time). We can't change the size of an array at runtime. So,
the queue will only work for a fixed number of elements.

Using Linked List:

 In a linked queue, each node of the queue consists of two parts i.e. data part and the
next part. Each element of the queue points to its immediate next element in the
memory.
 In the linked queue, there are two pointers maintained in the memory i.e. front
pointer and rear pointer. The front pointer contains the address of the starting
element of the queue while the rear pointer contains the address of the last element of
the queue.

1. Enqueue Function
void enqueue(int elt)
{
n=(struct node*)malloc(sizeof(struct node));
n->data=elt;
n->next=NULL;
if (front==NULL && rear==NULL)
front=rear=n;
else
{
rear->next=n;
rear=n;
}
printf("\n Insertion is sucessful");
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

2. Dequeue Function

void dequeue()
{
if(front==NULL && rear==NULL)
printf("Stack Underflow");
else
{
temp=front;
front=front->next;
if(front==NULL)
rear=NULL;
free(temp);
}
printf("Enqueue element sucessfully");
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 2 Data Structures And Algorithms

3. Traverse Or Display Function


void display()
{
temp=front;
if(front==NULL && rear==NULL)
printf("Queue Underflow");
else
{
while(temp!=NULL)
{
printf("\t %d",temp->data);
temp=temp->next;
}
}
}
******************************

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit 3- Linear Data Structure
Linear lists , Sequential and linked allocation, list ADT, array and linked
Implementations, Singly Linked List-Opertion-Insertion-Deletion, Doubly
Linked List-Operation-Insertion, Deletion.

Sequential Allocation
Sequential allocation refers to the arrays or a contiguous block of memory.
 It is hard to Insert and delete files and requires movement to do so.
 Space is wasted.
 Expensive.
 It requires less space as only information is stored.
 It cannot be extended or reduced as per the requirements.
 Similar amount of time is required to access every element.
 Elements are stored in consecutive memory locations.
 A direct route is present to reach element individually.

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


Linked Organization
The Linked allocation means the linked lists whose data structures are
connected by various nodes.
A node carries at least two pieces of information, some data and a reference
link (pointing to next field / node).
 Insertions and deletions can be done
easily without requiring any movement.
 Space is not wasted.
 Inexpensive.
 More space is required for the pointers
which are also stored along with
information.
 Size is not fixed.
 It can be extended or reduced
according to requirements.
 Different amount of time is required to
access every element.
 Elements might or might not be stored
in consecutive memory locations.
 There is no direct route to reach an
element.

Abstract Data Types


Abstract data type (ADT) is a specification of a set of data and the set of operations that
can beperformed on the data.
The abstract data type is written with the help of instances and operations. In ADT
instances represent the elements on which various operations can be performed.
Examples,
Array, stack, queue, tree, etc.,
Array as an ADT:
AbstractDataType Array
{
Instances:
An array A of some size, index i and total number of elements in the array n
Operations:
Store() – this operation stores the desired elements at each successive location.
Display() – this operation displays the elements of the array.
}

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


ADT is useful to handle the data type correctly. Always what is to be done is given in
ADT but how is to be done is not given in ADT. Note that we have only given what are the
operations in arrays in above example. But how it is to be done is not given.

List ADT
 A list is a ordered tuple of homogeneous elements
A0, A1, A2, …., An-1
where Ai is the i-th element of the list
 The position of element Ai is i; positions range from 0 to n-1 inclusive
 The size of a list is N (a list with no elements is called an “empty list”.

 Generic Operations on a list:


1. Create an empty list
2. printList – prints all elements in the list
3. find(x) – returns the position of the first occurrence of x.
4. remove(x) – removes x from the list if present
5. insert(x,postion) – inserts x into the list at the specified position.
6. isEmpty() – returns true if the list has no elements
7. findKth(int k) –returns the element in the specified position.
8. Sort() – sort the elements in ascending or descending order.

Array implementation of List


An array is a collection of elements of similar data type that are referred through a common
name. It is simply a grouping of similar data items.
The elements in the array are stored in contiguous memory locations. A specific element in
an array is accessed by an index or subscript. Subscript or index should not be negative. The first
element of array willhave index as zero.

One-Dimensional Arrays:
A list of items can be given one variable name using only one subscript and such a variable
is called single-subscripted variable or one dimensional array. A one dimensional array can
be declared as follows:

General syntax: Example:


Datatype array_name[size_of_array]; int a[7];

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


The array ‘a’ of size 7, has all the elements which are of integer type. Let us understand such an
arrangement of array elements by following figure 1.1

a[0] a[1] a[2] a[3] a[4] a[5] a[6]

10 20 30 40 50 60 70

Figure. 1.1 Array a[7]


Now let us see how to handle this array. We will write a simple C program in which we are
simply goingto store the elements and then we will print those stored elements.
#include<stdio.h>
void main()
{
int a[7],i;
printf(“\nEnter the Elements in an Array a:”);
for(i=0;i<=6;i++)
scanf(“%d”,&a[i]);
printf(“\n You have Stored these numbers in the array a:”);
for(i=0;i<=6;i++)
printf(“\n%d”,a[i]);
}

Memory Representation of One-Dimensional Array:


The array name holds the address of the first element. It is called as BASE ADDRESS
of that array. The base address can’t be modified during execution, because it is static.
Consider the first element is stored in the address of 1020. It will look like in figure 1.2,
int a[7];

Address 1020 1022 1024 1026 1028 1030 1032

10 20 30 40 50 60 70
Index 0 1 2 3 4 5 6

a[0] means a + 0  1020 + 0  1020 (locates the 1020)


a[1] means a + 1  1020 + 1 * size of datatype  1020 + 2  1022[ for ‘int’ size is 2 byte]
a[2] means a + 2  1020 + 2 * size of datatype  1020 + 4  1024
a[3] means a + 3  1020 + 3 * size of datatype  1020 + 6  1026
a[4] means a + 4  1020 + 4 * size of datatype  1020 + 8  1028

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


Array Implementation of List:
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
int a1, a[20], n, p, elt, f, i, pos,flag=0,s;
void create()
{
printf("\n Enter the number of nodes");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:");
scanf("%d",&a[i]);
}
}
void deletion()
{
printf("\n Enter the position u want to delete::");
scanf("%d", &pos);
if(pos>=n)
{
printf("\n Invalid Location::");
}
else
{
for(i=pos+1;i<n;i++)
a[i-1]=a[i];
n--;
}
printf("\n The Elements after deletion");
for(i=0;i<n;i++)
printf("\t%d", a[i]);
}
void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &s);
for(i=0;i<n;i++)
{
if(a[i]==s)
{
printf("Element Found at position %d",i);
break;
}
}
if(i==n)
printf("Not Found");
}

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


void insert()
{
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);
if(pos>=n)
printf("\n invalid Location::");
else
{
for(i=MAX-1;i>=pos-1;i--)
{
a[i+1]=a[i];
}
printf("\n Enter the element to insert::\n");
scanf("%d",&elt);
a[pos]=elt;
n++;
}
printf("\n The list after insertion::\n");
display();
}
void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
printf("\n\n%d", a[i]);
}
void main()
{
int ch;
char g='y';
do
{
printf("\n main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice");
scanf("%d", &ch);
switch(ch)
{
case 1: create(); break;
case 2: deletion(); break;
case 3: search(); break;
case 4: insert(); break;
case 5: display();break;
case 6: exit(0); break;
default: printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:::");
scanf("\n%c", &g);
}while(g=='y'||g=='Y');
}

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


Linked Lists implementation
A linked list is a linear collection of data elements, called nodes, where the linear order
is given by means of pointers.
Types of Linked Lists:
There are different kinds of linked list. They are
1. Singly Linked List
2. Circular Linked List
3. Two-way or doubly linked lists
4. Circular doubly linked lists
Singly-linked list
A singly linked list is a linear collection of data elements, called nodes. Each and every
node hastwo parts:
 The first part contains the information of the element i.e. INFO(DATA).
 The second part is NEXT, which contains the address of the next node in the list.

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


 The linked list consists of series of nodes, which are not necessarily adjacent in memory.
 A list is a dynamic data structure i.e. the number of nodes on a list may vary
dramatically aselements are inserted and removed.
 The pointer of the last node contains a special value, called the null pointer. This null
pointer
signals the end of list.
The list with no nodes on it is called the empty list or null list.
 Example:
The single linked list with 4 nodes is shown below:

Start/Head/First Node Last Node

10 20 30 40 Null

Figure. 1.2 Singly Linked List containing four integer values

Basic Operations:
1. Insertion
a. At first
b. At last
c. At a given location or given data item (At middle)
2. Deletion
a. First Node
b. Last Node
c. Node in given location or given data item
Initial Condition
HEAD or START = NULL;
Address of the first node in the list is stored in HEAD/START. Initially there is no node in the
list. So, HEAD/START is initialized to NULL (No address).

Insertion Operation
1. Insertion At First
void insert_at_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n Enter the data to insert at begin: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
start=newnode;
else
{
newnode->next=start;

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


start=newnode;
}
}
2. Insertion At Mid
void insert_at_end()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at end: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
{
start=newnode;
temp=newnode;
}
else
{
temp = start;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = newnode;
}
}
3. Insertion At End
void insert_mid()
{
int key;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n Enter the data to insert at middle: ");
scanf("%d",&newnode->data);
if(start==NULL)
start=newnode;
else
{
printf("\n Enter the element after which you want to insert: ");
scanf("%d",&key);
temp=start;
do
{
if(temp->data==key)
{
newnode->next=temp->next;
temp->next=newnode;

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


return;
}
else
temp=temp->next;
}while(temp!=NULL);
}
}

Deletion Operation
1. Delete At First
void del_at_beg()
{
temp=start;
start=start->next; /*First element deleted*/
free(temp);
}

2. Delete At Mid
void del_at_mid()
{
int key;
printf("\n Enter element to delete..");
scanf("%d",&key);
p=start;

while(p->next!= NULL)
{
if(p->next->data==key) /*Element deleted in between*/
{
temp=p->next;
p->next=temp->next;
free(temp);
}
p=p->next;
}
}

3. Delete At End
void del_at_end()
{
temp=start;
while(temp->next!= NULL)
{
p=temp;
temp=temp->next;
}
free(p->next);
p->next=NULL;
}

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


Circular-linked list
In a circular-linked list, the first and final nodes are linked together. This can be done
for both singly and doubly linked lists. To traverse a circular linked list, we begin at any node
and follow the list in either direction until we return to the original node.
Singly-circular-linked list
In a singly-circular-linked list, each node has one link, similar to an ordinary singly-
linked list,except that the next link of the last node points back to the first node.
First /Start/Head Node

10 20 30 40

****************
Doubly-Linked List
A more sophisticated kind of linked list is a doubly-linked list or two-way linked list,
in which each node has two links: one points to the previous node, or points to a null value or
empty list if it is the first node; and one points to the next, or points to a null value or empty list
if it is the final node.
*prev data *next

Null 15 56 27 Null
First Node Last Node
Figure : Doubly Linked List

Basic Operations:
1. Insertion
a. At first
b. At last
c. At a given location or given data item (At middle)
2. Deletion
a. First Node
b. Last Node
c. Node in given location or given data item

Insertion Operation
1. Insertion At First
void insert_at_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at begin: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
start=newnode;

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


else
{
newnode->next=start;
start->prev=newnode;
start=newnode;
}
}

2. Insertion At Mid
void insert_mid()
{
int key;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at middle: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
start=temp=newnode;
else
{
printf("\nEnter the element after which you want to insert: ");
scanf("%d",&key);
temp=start;
do
{
if(temp->data==key)
{
newnode->next=temp->next;
temp->next->prev=newnode;
temp->next=newnode;
newnode->prev=temp;
return;
}
else
temp=temp->next;
}while(temp!=NULL);
}
}

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


3. Insertion At End
void insert_at_end()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at last: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;
if(start==NULL)
start=temp=newnode;
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
newnode->prev=temp;
}
}
Deletion Operation
1. Delete At First
void del_at_beg()
{
temp=start;
start=start->next; /*First element deleted*/
free(temp);
start->prev=NULL;
}
2. Delete At Mid
void del_at_mid()
{
int key;
printf("\nEnter ele to delete..");
scanf("%d",&key);
p=start;
while(p->next!= NULL)
{
if(p->next->data==key)
{
temp=p->next;
p->next=temp->next;
temp->next->prev=p;
free(temp);
}

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


p=p->next;
}
}

3. Delete At End
void del_at_end()
{
temp=start;
while(temp->next!= NULL)
{
p=temp;
temp=temp->next;
} /*Last element deleted*/
free(temp);
p->next=NULL;
}
Doubly-circular-linked list
In a doubly-circular-linked list, each node has two links, similar to a doubly-linked
list, except that the previous link of the first node points to the last node and the next link of
the last node points to the first node. As in doubly-linked lists, insertions and removals can be
done at any point with access to any nearby node.

First Node Last Node

5 10 15 20

Figure 1.10 Doubly Circular Linked List


Advantages of Linked List
1. Linked List is dynamic data structure; the size of a list can grow or shrink during
the programexecution. So, maximum size need not be known in advance.
2. The Linked List does not waste memory
3. It is not necessary to specify the size of the list, as in the case of arrays.
4. Linked List provides the flexibility in allowing the items to be rearranged.
Pitfalls encountered in single linked list
1. A singly linked list allows traversal of the list in only one direction.
2. Deleting a node from a list requires keeping track of the previous node, that is, the
node whose link points to the node to be deleted.
3. If the link in any node gets corrupted, the remaining nodes of the list become unusable.
Applications of linked list
 To implement of Stack, Queue, Tree, Graph etc.,
 Polynomial Manipulation
 To maintain Free-Storage List in memory

***********************

RADHAKRISHNAN.P, Asst.Professor Dept of CS & AI , SR UNIVERSITY.


Unit - 4 Data Structures And Algorithms

UNIT IV

Non Linear data structures: Trees – Basic Terminology, Binary tree ADT, array and linked
representations, traversals, threaded binary trees, Priority Queues-Definition, ADT, Realizing a
Priority Queue using Heap.
Search Trees-Binary Search Trees, Definition, ADT, Implementation, Operations- Searching,
Insertion and Deletion, AVL Trees - Definition, Operations – Insertion and Searching,
B-Trees - Definition, B-Tree of order m, operations - insertion and deletion, Introduction to Red-
Black and Splay Trees, Comparison of Search Trees.

Tree

 In linear data structure, data is organized in sequential order and in non-linear data
structure; data is organized in random order.

 A tree data structure can be defined as follows...


Tree is a non-linear data structure which organizes data in hierarchical
structure and this is a recursive definition.

In a tree data structure, if we have N number of nodes then we can have a maximum of N-
1 number of links.

Example

Tree Terminology

1. Root
 In a tree data structure, the first node is called as Root Node.
 We can say that root node is the origin of tree data structure.
 In any tree, there must be only one root node. We never have multiple root nodes in a tree.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

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 predecessor of any node is called as PARENT
NODE.
 In simple words, the node which has branch from it to any other node is called as 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.

5. Siblings
 In a tree data structure, nodes which belong to same Parent are called as SIBLINGS.
 In simple words, the nodes with same parent are called as Sibling nodes.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

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.
 In a tree, leaf node is also called as 'Terminal' node.

7. Internal Nodes
 In a tree data structure, the node which has at least one child is called as INTERNAL
Node.
 In simple words, an internal node is a node with at least one child.
 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'

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

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 all leaf nodes is '0'.

In a tree, height of the root node is said to be height of the tree.

11. Depth
 In a tree data structure, the total number of edges from root node to a particular
node is called as DEPTH of that Node.

 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'.

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.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

12. Path
 In a tree data structure, the sequence of Nodes and Edges from one node to another
node is called as PATH between 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.

13. Sub Tree


 In a tree data structure, each child from a node forms a sub tree recursively.
 Every child node will form a sub tree on its parent node.

**************************
Types of Trees
1. Binary Tree
2. Binary Search Tree
3. AVL Tree
4. B-Tree etc.,
1.Binary Tree
 In a normal tree, every node can have any number of children.
 Binary tree is a special type of tree data structure in which every node can have a
maximum of 2 children.
 One is known as left child and the other is known as right child.

A tree in which every node can have a maximum of two children is called as Binary Tree.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

In a binary tree, every node can have either 0 children or 1 child or 2 children but not more
than 2 children.
Example

There are different types of binary trees and they are...

a) Strictly Binary Tree


 A binary tree in which every node has either two or zero number of children is called
Strictly Binary Tree

Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-Tree

Strictly binary tree data structure is used to represent mathematical expressions.


Example

b) Complete Binary Tree

 A binary tree in which every internal node has exactly two children and all leaf nodes
are at same level is called Complete Binary Tree.
 But in strictly binary tree, every node should have exactly two children or none and in
complete binary tree all the nodes must have exactly two children and at every level of
complete binary tree there must be 2level number of nodes.
 For example at level 2 there must be 22 = 4 nodes and at level 3 there must be 23 = 8 nodes.

Complete binary tree is also called as Perfect Binary Tree

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

c) Almost Complete Binary Tree (ACBT)

An almost complete binary tree is a binary tree that satisfies the following 2 properties-
 All the levels are completely filled except possibly the last level.
 The last level must be strictly filled from left to right.
Example

Not ACBT ACBT


Here,
 First binary tree is not an almost complete binary tree.
 This is because the last level is not filled from left to right.

d) Extended Binary Tree

 A binary tree can be converted into Full Binary tree by adding dummy nodes to
existing nodes wherever required.
 The full binary tree obtained by adding dummy nodes to a binary tree is called as
Extended Binary Tree

In above figure, a normal binary tree is converted into full binary tree by adding dummy nodes (In
pink color).

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

E) Degenerate or Pathological Tree


 A degenerate or pathological tree is the tree having a single child either left or right.

Degenerate Binary Tree


e) Skewed Binary Tree
 A skewed binary tree is a pathological/degenerate tree in which the tree is either
dominated by the left nodes or the right nodes.
 Thus, there are two types of skewed binary tree: left-skewed binary tree and right-
skewed binary tree.

Left Skewed Right Skewed


f) Balanced Binary Tree
 It is a type of binary tree in which the difference between the height of the left and the
right sub tree for each node is either 0 or 1.

Balanced Binary Tree

**************************

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Binary Tree Representations


A binary tree data structure is represented using two methods.
1. Array Representation
2. Linked List Representation
Consider the following binary tree...

1. Array Representation
 In array representation of binary tree, we use a one dimensional array (1-D Array) to
represent binary tree.Consider the above example of binary tree and it is represented as
follows...

To represent a binary tree of depth 'n' using array representation, we need one dimensional array
with a maximum size of 2n+1 - 1.

2. Linked List Representation


 We use double linked list to represent a binary tree.
 In a double linked list, every node consists of three fields. First field for storing left child
address, second for storing actual data and third for storing right child address.
 In this linked list representation, a node has the following structure.

 The above example of binary tree represented using Linked list representation is shown as
follows...

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Program For Binary Tree:


#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node* left;
struct node* right;
}*node,*root;

// Creation
/* newnode() allocates a newnode with the given data and NULL left & right pointers. */

struct node* newnode(int data)


{
// Allocate memory for new node
node= (struct node*)malloc(sizeof(struct node));

// Assign data to this node


node->data = data;

// Initialize left and


// right children as NULL
node->left = NULL;
node->right = NULL;
return (node);
}

/* Display */

void inorder(struct node* root)


{
if (root == NULL) return;
inorder(root->left);
printf("%d ->", root->data);
inorder(root->right);
}

int main()
{
/*create root*/
root = newnode(1);

/* following is the tree after above


statement
1
/\
NULL NULL
*/

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

root->left = newnode(2);
root->right = newnode(3);
/* 2 and 3 become left and right children
of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = newnode(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/\
NULL NULL
*/
inorder(root);
return 0;
}

OUTPUT
4 ->2 ->1 ->3 ->
***************************
Binary Tree Traversals
 When we wanted to display a binary tree, we need to follow some order in which all the
nodes of that binary tree must be displayed.
 Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree
Traversal.

There are three types of binary tree traversals.


1. In - Order Traversal (LDR)
2. Pre - Order Traversal (DLR)
3. Post - Order Traversal (LRD)

Steps or Algorithm C Implementation


1. In-order Traversal: (LDR) void inorder(struct node *rootnode)
 Traverse the left-subtree. {
 Display or print the root(node/data). if(rootnode)
 Traverse the right-subtree. {
inorder(rootnode->left);
printf("%d-->",rootnode->data);
inorder(rootnode->right);
}
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

2. Pre-order Traversal: (DLR) void preorder(struct node *rootnode)


 Display or print the root(node/data). {
 Traverse the left-subtree. if (rootnode)
 Traverse the right-subtree. {
printf("%d-->",rootnode->data);
preorder(rootnode->left);
preorder(rootnode->right);
}
}
3. Post-order Traversal: (LRD) void postorder(struct node *rootnode)
 Traverse the left-subtree. {
 Traverse the right-subtree. if(rootnode)
 Display or print the root(node/data). {
postorder(rootnode->left);
postorder(rootnode->right);
printf("%d-->",rootnode->data);
}
}
EXAMPLE OUTPUT

Preorder Traversal: A - B - D - I - J - F - C - G - K – H
In order Traversal : I - D - J - B - F - A - G - K - C - H
Post order Traversal: I - J - D - F - B - K - G - H - C - A

Post order Traversal: 4 5 2 6 7 3 1

*********************
Threaded Binary Tree
In threaded binary tree, NULL pointers are replaced by references to other nodes in the
tree, called threads.

Definition:

Threaded Binary Tree is also a binary tree in which


 all left child pointers that are NULL (in Linked list representation) points to its
in-order predecessor, and
 all right child pointers that are NULL (in Linked list representation) points to its
in-order successor.

General Binary Tree Threaded Binary Tree


In a general binary trees, the NULL pointers In Threaded Binary Tree, the NULL pointers are
remains NULL. used as thread
We can’t use NULL pointers so it is wastage of We can use the NULL pointers which is an
memory. efficient way to use computers memory.
Traverse is not easy and not memory efficient. Traversal is easy. Completed without using stack or
recursive function.
Less complex than Threaded Binary Tree Structure is complex.
Less time consuming than Threaded Binary Tree. Insertion and Deletion takes more times.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Example for General Binary Tree Example for Threaded Binary Tree

Types of Threaded Binary Tree

Inorder Traversal :- D,B,E,A,F,C,G

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Example (Threaded Binary Tree)

Advantage:-
1. By doing threading we avoid the recursive method of traversing a tree , which doesn’t use
of stack and consumes a lot of memory and time.
2. The node can keep record of its root.
3. Backward Traverse is possible.
4. Applicable in most types of the binary tree.
Disadvantage:-
1. Tree traversal algorithm becomes complex.
2. Extra space needed to store boolean values.
3. Inseration and deletion operation becomes more difficult.
*******************************

Priority Queue
Priority Queue is an extension of the queue with the following properties:
1. Every item has a priority associated with it.
2. An element with high priority is dequeued before an element with low priority.
3. If two elements have the same priority, they are served according to their order in the
queue.

Heaps:
A heap is a specific tree based data structure in which all the nodes of tree are in a specific
order. Let’s say if X is a parent node of Y, then the value of X follows some specific order with
respect to value of Y and the same order will be followed across the tree.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Binary Heap
A binary heap is a type of binary tree (but not a binary search tree) that has the following
properties:

1. Shape: It is a complete tree. (Remember that a complete binary tree is one where every
level except the last one is completely filled, and the last level has all leaves as far left
as possible.)
2. Order (heap): The parent of a node is ≥ all of its children (for a max heap) or ≤ all of
its children (for a min heap).
There can be two types of binary heap:

Max Heap: In this type of heap, the value of parent node will always be greater than or
equal to the value of child node across the tree and the node with highest value will be the root
node of the tree.

Min Heap: In this type of heap, the value of parent node will always be smaller than or
equal to the value of child node across the tree and the node with smallest value will be the root
node of the tree.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Priority Queue Operations

1. Inserting an Element into the Priority Queue


Inserting an element into a priority queue (max-heap) is done by the following steps.
 Insert the new element at the end of the tree.
 Steps:
If there is no node,
create a newNode.
else (a node is already present)
insert the newNode at the end (last node from left to right.)
heapify the Node.

Insertion Heapify after Insertion

2.Deleting
Remove min: The minimum value is stored at the root of the tree. But the root of the
tree cannot be directly removed. First, it is replaced with any one of the leaves and then
removed.
Step 1 Step 2

Step 3 Step 4

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Steps
If there is no node,
Unable to delete.
Else (a node is already present)
Remove or delete the root node , replace with lastLeafNode.
heapify the node
Priority Queue Applications
 Dijkstra's algorithm
 for load balancing and interrupt handling in an operating system
 for data compression in Huffman code
************************

Binary Search Tree


 A binary tree to be a binary search tree , the data of all the nodes in the left sub-tree of the
root node should be less than the data of the root.
 The data of all nodes in the right subtrees of the root node should be greater than equal to
the data of the root.
 Key property is value at node
o Smaller values in left subtrees
o Larger values in right subtrees
 A data structure for efficient
searching , insertion and deletion.

Diagram of Binary Search Tree


Example for BST

Application of BST

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

1. Inserting an Element into Binary Search Tree:

The insert operation adds element to an existing binary search tree.

C implementation (insert)
struct node* insert(struct node *node, int data)
{
if (node == NULL)
return newnode(data);
if (data < node->data)
node->left = insert(node->left,data);
else if (data > node->data)
node->right = insert(node->right,data);
return node;
}

2.Searching an Element in BST


It is often required to find whether a key is there in the tree. If the key is found in the node T, the
function returns the address of T or NULL if there is no such node.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

C implementation (Search)
struct node* search(struct node *node, int s)
{
if(node==NULL || node->data==s)
return node;
else if(s > node->data)
return search(node->right,s);
else
return search(node->left,s);
}

Find Minimum and Maximum Element in a BST


Finding Minimum Element in a BST Finding Maximum Element in a BST
 Minimum element lies as the left most  Maximum element lies as the right
node in the left most branch starting most node in the right most branch
from the root. starting from the root.
 To reach the node with minimum  To reach the node with maximum
value, we need to traverse the tree value, we need to traverse the tree
from root along the left branch till we from root along the right branch till
get a node with a null / empty left sub we get a node with a null / empty right
tree. sub-tree.

3. Deleting an Element in BST:


The node to be deleted can fall into any one of the following categories;
1. Node may not have any children ( i.e., it is a leaf node)
2. Node may have only one child ( either left / right child)
3. Node may have two children ( both left and right)

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

C implementation (deletion)
struct node* del(struct node *node, int x)
{
if(node==NULL)
return NULL;
if(x>node->data)
node->right= del(node->right, x);
else if(x<node->data)
node->left = del(node->left, x);

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

else
{
//No Children
if(node->left==NULL && node->right==NULL)
{
free(node);
return NULL;
}

//One Child
else if(node->left==NULL || node->right==NULL)
{
if(node->left==NULL)
temp = node->right;
else
temp = node->left;
free(node);
return temp;
}

//Two Children
else
{
temp = findmin(node->right);
node->data = temp->data;
node->right = del(node->right, temp->data);
}
}
return node;
}
Example (BST)
Construct a Binary Search Tree by inserting the following sequence of numbers...
10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as follows...

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Balanced Binary Tree


 The disadvantage of a binary search tree is that its height can be as large as N-1.
 This means that the time needed to perform insertion and deletion and many other
operations can be O(n) in the worst case.
 Let us consider an example. If we have the following tree with keys 10,20,30,40,50,60,70
then a binary tree would look like this:

*****************************
AVL TREE
 AVL tree is a self-balanced binary search tree.
 A binary tree is said to be balanced, if the difference between the heights of left and right
subtrees of every node in the tree is either -1, 0 or 1.
 In an AVL tree, every node maintains a extra information known as balance factor.
 The AVL tree was introduced in the year of 1962 by G.M. Adelson-Velsky and
E.M.Landis.

Definition
An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every node
is either 1, 0 or 1.
Balance factor = height Of Left Subtree – height Of Right Subtree

The above tree is a binary search tree and every node is satisfying balance factor condition. So this
tree is said to be an AVL tree.

Every AVL Tree is a binary search tree but all the Binary Search Trees need not to be AVL
trees.

AVL Tree Rotations


 In AVL tree, after performing every operation like insertion and deletion we need to
check the balance factor of every node in the tree.
 If every node satisfies the balance factor condition then we conclude the operation
otherwise we must make it balanced.
 We use rotation operations to make the tree balanced whenever the tree is becoming
imbalanced due to any operation.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

 Rotation operations are used to make a tree balanced.


 Rotation is the process of moving the nodes to either left or right to make tree balanced.
 There are four rotations and they are classified into two types.

AVL Rotations
Single Rotation
1) LL Rotation
2) RR Rotation
Double Rotation
3) LR Rotation
4) RL Rotation
LL Rotation( Right Side Rotation)

C Routine to Rotate Right:


node * rotateright(node *k2)
{
node *k1;
k1=k2->left;
k2->left=k1->right;
k1->right=k2;
k2->ht=height(k2);
k1->ht=height(k1);
return(k1);
}
node *ll(node *t)
{
t=rotateright(t);
return(t);
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

RR Rotation (Left Side rotation)

C Routine to Rotate Left:


node * rotateleft(node *k1)
{
node *k2;
k2=k1->right;
k1->right=k2->left;
k2->left=k1;
k1->ht=height(k1);
k2->ht=height(k2);
return(k2);
}
node * rr(node *t)
{
t=rotateleft(t);
return(t);
}
Left-Right Rotation(LR Rotation)

A node has been We first perform the Node C is still We shall now right-rotate The tree is now
inserted into the left rotation on the left unbalanced, however the tree, making B the new balanced.
right subtree of the subtree of C. This now, it is because of the root node of this subtree. C
left subtree. This makes A, the left left-subtree of the left- now becomes the right
makes C an subtree of B. subtree. subtree of its own left
unbalanced node. subtree.
These scenarios cause
AVL tree to perform
left-right rotation.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

C Routine to perform Left-Right Double Rotation:


node *lr(node *k3)
{
k3->left=rotateleft(k3->left);
k3=rotateright(k3);
return(k3);
}

Right-Left Rotation

A node has been First, we perform the Node A is still A left rotation is The tree is now balanced.
inserted into the right rotation along C unbalanced because of performed by making B
left subtree of the node, making C the right the right subtree of its the new root node of the
right subtree. subtree of its own left right subtree and subtree. A becomes the
This makes A, an subtree B. Now, B requires a left rotation. left subtree of its right
unbalanced node becomes the right subtree B.
with balance subtree of A.
factor 2.

Routine to perform Right to Left Double Rotation:


node *rl(node *t)
{
t->right=rotateright(t->right);
t=rotateleft(t);
return(t);
}

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Operations on an AVL Tree


The following operations are performed on an AVL tree...
1. Search 2.Insertion 3.Deletion
1. Search Operation in AVL Tree
In an AVL tree, the search operation is performed with O(log n) time complexity. The search
operation is performed similar to Binary search tree search operation. We use the following steps
to search an element in AVL tree...
 Step 1: Read the search element from the user
 Step 2: Compare, the search element with the value of root node in the tree.
 Step 3: If both are matching, then display "Given node found!!!" and terminate the
function
 Step 4: If both are not matching, then check whether search element is smaller or larger
than that node value.
 Step 5: If search element is smaller, then continue the search process in left subtree.
 Step 6: If search element is larger, then continue the search process in right subtree.
 Step 7: Repeat the same until we found exact element or we completed with a leaf node
 Step 8: If we reach to the node with search value, then display "Element is found" and
terminate the function.
 Step 9: If we reach to a leaf node and it is also not matching, then display "Element not
found" and terminate the function.
C implementation for Search Operation
struct node* search(struct node *rootnode, int s)
{
if(rootnode==NULL || rootnode->data==s)
return rootnode;
else if(s > rootnode->data)
return search(rootnode->right,s);
else
return search(rootnode->left,s);
}
2. Insertion Operation in AVL Tree
In an AVL tree, the insertion operation is performed with O(log n) time complexity. In AVL Tree,
new node is always inserted as a leaf node. The insertion operation is performed as follows...
 Step 1: Insert the new element into the tree using Binary Search Tree insertion logic.
 Step 2: After insertion, check the Balance Factor of every node.
 Step 3: If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
 Step 4: If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be
imbalanced. Then perform the suitable Rotation to make it balanced. And go for next
operation.
C implementation for Insertion Operation
node*insert(node*T,int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

if(x>T->data)
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x<T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
Example: Construct an AVL Tree by inserting numbers from 1 to 8.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

3. Deletion Operation in AVL Tree


 In an AVL Tree, the deletion operation is similar to deletion operation in BST. But
after every deletion operation we need to check with the Balance Factor condition.
 If the tree is balanced after deletion then go for next operation otherwise perform the
suitable rotation to make the tree Balanced.

Representation of AVL Trees:


 In order to represent a node in an AVL tree, a new field must be introduced for tree node.
This additional field stores the height of a node.
 A node in an AVL tree can be defined as:

typedef struct node


{
int data;
struct node*left,*right;
int ht;
}node;

Height of a node:
Height of a node can be calculated from the following C routine:
int height(node*T)
{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

if(lh>rh)
return(lh);

return(rh);
}

Balance Factor:
 For each AVL-tree node balance factor is need to be calculated.
 The balance factor keeps track of the relative height difference between its left and right
subtrees,i.e.,
Balance Factor(BF) = height(left subtree) - height(right subtree).
 Each node in a balanced binary tree has a balance of 1, - 1, or 0, depending on whether
the height of its left sub tree is greater than, less than, or equal to the height of its right sub
tree.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

C Routine for calculating Balance Factor of a node:


int BF(node*T)
{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}

AVL Rotation(With Detailed Diagram)


To maintain the height balanced property of the AVL tree after insertion or deletion, it is
necessary to perform a tree rotation on the tree.
 These imbalances can be overcome by
1. Single Rotation (in case of LL and RR)
2. Double Rotation (in case of LR and RL)

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Advantages:
1. Search is O(log n) since AVL trees are always balanced.
2. Insertion and deletions are also O(log n)
3. The height balancing adds no more than a constant factor to the speed of insertion.
Disadvantages:
1. Difficult to program & debug; more space for balance factor.
2. Asymptotically faster but rebalancing costs time.
3. Most large searches are done in database systems on disk and use other structures (e.g.
B-trees).
*********************
B - Tree
 In search trees like binary search tree, AVL Tree, Red-Black tree, etc., every node contains
only one value (key) and a maximum of two children.
 But there is a special type of search tree called B-Tree in which a node contains more
than one value (key) and more than two children.
 B-Tree was developed in the year 1972 by Bayer and McCreight with the name Height
Balanced m-way Search Tree. Later it was named as B-Tree.

B-Tree can be defined as follows...

B-Tree is a self-balanced search tree in which every node contains multiple keys and has
more than two children.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Note:-
Here, the number of keys in a node and number of children for a node depends on the order
of B-Tree. Every B-Tree has an order.

B-Tree of Order m has the following properties...

 Property #1 - All leaf nodes must be at same level.


 Property #2 - All nodes except root must have at least [m/2]-1 keys and maximum
of m-1 keys.
 Property #3 - All non leaf nodes except root (i.e. all internal nodes) must have at
least m/2 children.
 Property #4 - If the root node is a non leaf node, then it must have atleast 2 children.
 Property #5 - A non leaf node with n-1 keys must have n number of children.
 Property #6 - All the key values in a node must be in Ascending Order.

For example, B-Tree of Order 4 contains a maximum of 3 key values in a node and
maximum of 4 children for a node.

Operations on a B-Tree
The following operations are performed on a B-Tree...
1. Search
2. Insertion
3. Deletion

Search Operation in B-Tree


 The search operation in B-Tree is similar to the search operation in Binary Search
Tree. In a Binary search tree, the search process starts from the root node and we
make a 2-way decision every time (we go to either left subtree or right subtree).
 In B-Tree also search process starts from the root node but here we make an n-way
decision every time.
 Where 'n' is the total number of children the node has. In a B-Tree, the search
operation is performed with O(log n) time complexity.

 The search operation is performed as follows...

 Step 1 - Read the search element from the user.


 Step 2 - Compare the search element with first key value of root node in the
tree.
 Step 3 - If both are matched, then display "Given node is found!!!" and
terminate the function

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

 Step 4 - If both are not matched, then check whether search element is smaller
or larger than that key value.
 Step 5 - If search element is smaller, then continue the search process in left
subtree.
 Step 6 - If search element is larger, then compare the search element with next
key value in the same node and repeate steps 3, 4, 5 and 6 until we find the
exact match or until the search element is compared with last key value in the
leaf node.
 Step 7 - If the last key value in the leaf node is also not matched then display
"Element is not found" and terminate the function.

Insertion Operation in B-Tree


In a B-Tree, a new element must be added only at the leaf node. That means, the new
keyValue is always attached to the leaf node only. The insertion operation is performed as
follows...

 Step 1 - Check whether tree is Empty.


 Step 2 - If tree is Empty, then create a new node with new key value and insert it into
the tree as a root node.
 Step 3 - If tree is Not Empty, then find the suitable leaf node to which the new key
value is added using Binary Search Tree logic.
 Step 4 - If that leaf node has empty position, add the new key value to that leaf node
in ascending order of key value within the node.
 Step 5 - If that leaf node is already full, split that leaf node by sending middle value to
its parent node. Repeat the same until the sending value is fixed into a node.
 Step 6 - If the spilting is performed at root node then the middle value becomes new
root node for the tree and the height of the tree is increased by one

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Delete Operation
The delete operation has more rules than insert and search operations.

The following algorithm applies:


 Run the search operation and find the target key in the nodes
 Three conditions applied based on the location of the target key, as explained in the
following sections

Case 1:- If the target key is in the leaf node


 Target is in the leaf node, more than min keys.
 Deleting this will not violate the property of B Tree
 Target node can borrow key from immediate left node, or immediate right node (sibling)
 The sibling will say yes if it has more than minimum number of keys
 The key will be borrowed from the parent node, the max value will be transferred to a
parent, the max value of the parent node will be transferred to the target node, and remove
the target value
 Target is in the leaf node, but no siblings have more than min number of keys
 Search for key

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

 Merge with siblings and the minimum of parent nodes


 Total keys will be now more than min
 The target key will be replaced with the minimum of a parent node

Case 2:- If the target key is in an internal node


 Either choose, in- order predecessor or in-order successor
 In case the of in-order predecessor, the maximum key from its left subtree will be selected
 In case of in-order successor, the minimum key from its right subtree will be selected
 If the target key’s in-order predecessor has more than the min keys, only then it can replace
the target key with the max of the in-order predecessor
 If the target key’s in-order predecessor does not have more than min keys, look for in-
order successor’s minimum key.
 If the target key’s in-order predecessor and successor both have less than min keys, then
merge the predecessor and successor.

Case 3:- If the target key is in a root node


 Replace with the maximum element of the in-order predecessor subtree
 If, after deletion, the target has less than min keys, then the target node will borrow max
value from its sibling via sibling’s parent.
 The max value of the parent will be taken by a target, but with the nodes of the max value
of the sibling.
Now, let’s understand the delete operation with an example.

The above diagram displays different cases of delete operation in a B-Tree. This B-Tree is of order
5, which means that the minimum number of child nodes any node can have is 3, and the
maximum number of child nodes any node can have is 5. Whereas the minimum and a maximum
number of keys any node can have are 2 and 4, respectively.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

In the above example:

 The target node has the target key to delete


 The target node has keys more than minimum keys
 Simply delete the key

In the above example:

 The target node has keys equal to minimum keys, so cannot delete it directly as it will
violate the conditions

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Now, the following diagram explains how to delete this key:

 The target node will borrow a key from immediate sibling, in this case, in-order
predecessor (left sibling) because it does not have any in-order successor (right sibling)
 The maximum value of the inorder predecessor will be transferred to the parent, and the
parent will transfer the maximum value to the target node (see the diagram below)

The following example illustrates how to delete a key that needs a value from its in-order
successor.

 The target node will borrow a key from immediate sibling, in this case, in-order successor
(right sibling) because it’s in-order predecessor (left sibling) has keys equal to minimum
keys.
 The minimum value of the in-order successor will be transferred to the parent, and the
parent will transfer the maximum value to the target node.

In the example below, the target node does not have any sibling that can give its key to the target
node. Therefore, merging is required.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

See the procedure of deleting such a key:

 Merge the target node with any of its immediate siblings along with parent key
 The key from the parent node is selected that siblings in between the two merging
nodes
 Delete the target key from the merged node.

*********************
Red Block Tree
 RBT Tree was invented in 1972 by Rudolf Bayer. It is a kind of BST and AVL tree
(Balancing Tree).
 Red - Black Tree is another variant of Binary Search Tree in which every node is
colored either RED or BLACK.
We can define a Red Black Tree as follows...
Red Black Tree is a Binary Search Tree in which every node is colored either RED or
BLACK.

Properties of Red Black Tree

 Property #1: Red - Black Tree must be a Binary Search Tree.


 Property #2: The ROOT node must be colored BLACK.
 Property #3: The children of Red colored node must be colored BLACK. (There should
not be two consecutive RED nodes).

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

 Property #4: In all the paths of the tree, there should be same number of BLACK colored
nodes.
 Property #5: Every new node must be inserted with RED color.
 Property #6: Every leaf (e.i. NULL node) must be colored BLACK.

Example
Following is a Red-Black Tree which is created by inserting numbers from 1 to 9.

Every Red Black Tree is a binary search tree but every Binary Search Tree need not be Red
Black tree
Insertion into RED BLACK Tree

 In a Red-Black Tree, every new node must be inserted with the color RED. The insertion
operation in Red Black Tree is similar to insertion operation in Binary Search Tree.
 But it is inserted with a color property. After every insertion operation, we need to check
all the properties of Red-Black Tree.
 If all the properties are satisfied then we go to next operation otherwise we perform the
following operation to make it Red Black Tree.

 1. Recolor
 2. Rotation
 3. Rotation followed by Recolor

The insertion operation in Red Black tree is performed using the following steps...

 Step 1 - Check whether tree is Empty. If tree is Empty then insert the newNode as Root
node with color Black and exit from the operation.
 Step 2 - If tree is not Empty then insert the newNode as leaf node with color Red.
 Step 3 - If the parent of newNode is Black then exit from the operation.
 Step 4 - If the parent of newNode is Red then check the color of parentnode's sibling of
newNode.
o 4(a) If it is colored Black or NULL then make suitable Rotation (hint –
o consider two movement node) and Recolor it.
o 4(b) If it is colored Red then perform Recolor(Black) & also check if parent’s
parent(i.e grand parent) of new node is not root node then recolor it & recheck
 Step 5 - Repeat the same until tree becomes Red Black Tree.
Check :-
 Root node is black
 No two consecutive RED nodes
 Count number of block node in all path, it should be same.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Deletion Operation in Red Black Tree


 The deletion operation in Red-Black Tree is similar to deletion operation in BST. But after
every deletion operation, we need to check with the Red-Black Tree properties. If any of
the properties are violated then make suitable operations like Recolor, Rotation and
Rotation followed by Recolor to make it Red-Black Tree.
********************
Splay Tree Data structure
 Splay tree is another variant of a binary search tree. In a splay tree, recently accessed
element is placed at the root of the tree.
 A splay tree is defined as follows...
Splay Tree is a self - adjusted Binary Search Tree in which every operation on
element rearranges the tree so that the element is placed at the root position of the
tree.
In a splay tree, every operation is performed at the root of the tree. All the operations in splay tree
are involved with a common operation called "Splaying".
Splaying an element, is the process of bringing it to the root position by performing suitable
rotation operations.
 In a splay tree, splaying an element rearranges all the elements in the tree so that splayed
element is placed at the root of the tree.
 By splaying elements we bring more frequently used elements closer to the root of the tree
so that any operation on those elements is performed quickly.
 That means the splaying operation automatically brings more frequently used elements
closer to the root of the tree.
 Every operation on splay tree performs the splaying operation.
 For example, the insertion operation first inserts the new element using the binary search
tree insertion process, then the newly inserted element is splayed so that it is placed at the
root of the tree. The search operation in a splay tree is nothing but searching the element
using binary search process and then splaying that searched element so that it is placed at
the root of the tree.

In splay tree, to splay any element we use the following rotation operations...

Rotations in Splay Tree

 1. Zig Rotation
 2. Zag Rotation
 3. Zig - Zig Rotation
 4. Zag - Zag Rotation
 5. Zig - Zag Rotation
 6. Zag - Zig Rotation

Zig Rotation
The Zig Rotation in splay tree is similar to the single right rotation in AVL Tree rotations. In zig
rotation, every node moves one position to the right from its current position. Consider the
following example...

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Zag Rotation
The Zag Rotation in splay tree is similar to the single left rotation in AVL Tree rotations. In zag
rotation, every node moves one position to the left from its current position. Consider the
following example...

Zig-Zig Rotation
The Zig-Zig Rotation in splay tree is a double zig rotation. In zig-zig rotation, every node moves
two positions to the right from its current position. Consider the following example...

Zag-Zag Rotation
The Zag-Zag Rotation in splay tree is a double zag rotation. In zag-zag rotation, every node
moves two positions to the left from its current position. Consider the following example...

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

Zig-Zag Rotation
The Zig-Zag Rotation in splay tree is a sequence of zig rotation followed by zag rotation. In zig-
zag rotation, every node moves one position to the right followed by one position to the left from
its current position. Consider the following example...

Zag-Zig Rotation
The Zag-Zig Rotation in splay tree is a sequence of zag rotation followed by zig rotation. In zag-
zig rotation, every node moves one position to the left followed by one position to the right from
its current position. Consider the following example...

Every Splay tree must be a binary search tree but it is need not to be balanced tree.
Insertion Operation in Splay Tree
The insertion operation in Splay tree is performed using following steps...

 Step 1 - Check whether tree is Empty.


 Step 2 - If tree is Empty then insert the newNode as Root node and exit from the
operation.
 Step 3 - If tree is not Empty then insert the newNode as leaf node using Binary Search tree
insertion logic.
 Step 4 - After insertion, Splay the newNode

Deletion Operation in Splay Tree


The deletion operation in splay tree is similar to deletion operation in Binary Search Tree. But
before deleting the element, we first need to splay that element and then delete it from the root
position. Finally join the remaining tree using binary search tree logic.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 4 Data Structures And Algorithms

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

Non Linear Data Structures Part 2:


Graphs – Introduction, Basic Terminology, Graph Representations- Adjacency matrix, Adjacency
lists, Adjacency multilists, Graph traversals- DFS and BFS, Disjoint Sets, Union and Find
algorithms, Spanning Trees – kruskals, prims algorithms.

Graph
 Graph is a nonlinear data structure.
 Graph => G={V,E}
o V=set of vertex ={v1,v2,….vn}
o E=set of edges={e1,e2….en}
 Graph has no hierarchical relationship.
 If a tree contains a closed loop or circuit, it is a
graph.
Vertex / Vertices
A node in a graph
Edge Graph
A line which connects two vertices.

Basic Terminology
1.Arc 2.Loop
The edge in a directed graph. Ex:- A->B A special case of a cycle in which a single
Arc arc begins and ends with the same vertex.

3.Parallel Edges 4.Isomorphic Graph


Two edges are connected with two vertices. One graph is able to represent several
styles is called isomorphic graph.

Graph (a) and (b) are same , because edges and


5.Cycle vertices are same in both graphs.

It is a path that starts and ends with same vertex.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

7.Degree of a vertex

8.Path

9. Adjacent node
Two nodes are adjacent if they connected via edge.

10. Tree – It’s an acyclic graph.


11. Forest – It’s a disjoint set of trees.
12. Spanning Tree – A spanning tree is defined for a connected graph. It’s a subgraph that contains
all the vertices.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

Types of Graph
1.Trivial Graph
A graph with only one vertex is called a Trivial Graph.

2.NULL Graph
A null graph does not contain any edges in it.

3. Non-Directed Graph (Undirected Graph)


 A graph in which all the edges are undirected is called as a non-directed graph.
 In other words, edges of an undirected graph do not contain any direction.
Example-

Here,
 This graph consists of four vertices and four undirected edges.

4. Directed Graph-
 A graph in which all the edges are directed is called as a directed graph.
 Directed graphs are also called as digraphs.

Here,
 Since all the edges are directed, therefore it is a directed graph

5. Connected Graph-
 A graph in which we can visit from any one vertex to any other vertex is called as a
connected graph.
 In connected graph, at least one path exists between every pair of vertices.
Here,
 In this graph, we can visit from any one vertex to
any other vertex.
 There exists at least one path between every pair of
vertices.

6. Disconnected Graph (Unconnected Graph)-


 A graph in which there does not exist any path between at least one pair of vertices is
called as a disconnected graph.
Example-

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

7. Regular Graph-
 A graph in which degree of all the vertices is same is called as a regular graph.
 If all the vertices in a graph are of degree ‘k’, then it is called as a “k-regular graph“.
In these graphs,
 All the vertices have degree-2.
 Therefore, they are 2-Regular
graphs.

8. Complete Graph-
A complete graph is a graph in which each pair of graph vertices is connected by an edge.

9. Simple Graph-
A graph having no self loops and no parallel edges in it is called as a simple graph.

Example-
Here,

 This graph consists of three vertices and three edges.


 There are neither self loops nor parallel edges.
 Therefore, it is a simple graph.

10.Multi Graph-
A graph having no self loops but having parallel edge(s) in it is called as a multi graph.
Example-
Here,

 This graph consists of three vertices and four edges


out of which one edge is a parallel edge.
 There are no self loops but a parallel edge is present.
 Therefore, it is a multi graph.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

11.Cyclic and Acyclic Graph

12.Directed Acyclic Graph

12. Weighted Graph and Unweighted Graph


 In a weighted graph, all edges have some associated cost.
 In an unweighted graph, there is no associated cost to the edges. It just tells whether the two
nodes are connected or not.

Applications of Graphs
1. It used to represent communication network.
2. It used to represent electrical networks.
3. Graph coloring
4. Solving puzzles
5. Linguistics- The parsing tree of a language, Grammar of language.
6. Science-Molecular structure, Chemical structure, DNA structure.
---------------------------------------------------
Graph Representation
A graph can be represented using 3 data structures-
 Adjacency matrix
 Adjacency list
 Adjacency multilists.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

1.Adjacency Matrix
o Adjacency matrix is a sequential representation.
o It is used to represent which nodes are adjacent to each other. i.e. is there any edge
connecting nodes to a graph.
o In this representation, we have to construct a nXn matrix A. If there is any edge from a
vertex i to vertex j, then the corresponding element of A, ai,j = 1, otherwise ai,j= 0.(Or) If two
vertices are adjacent (there is an edge between them) the matrix insect has a value of 1 ,
otherwise , it is zero.
o Types of Adjacency Matrix:-
(1) Undirected Graph Representation

(2) Directed Graph Representation

In the above example, 1 represents an edge from row vertex to column vertex, and 0
represents no edge from row vertex to column vertex.

(3) Undirected Weighted Graph Representation

2.Adjacency list
 In Adjacency List, we use an array of a list to represent the graph.
 The list size is equal to the number of vertex(n).
 Let's assume the list of size n as Adjlist[n]
 Adjlist[0] will have all the nodes which are connected to vertex 0.
 Adjlist[1] will have all the nodes which are connected to vertex 1 and so on.

 Types of adjacency list

1. Undirected Graph Adjacency List

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

2. Directed Graph Adjacency List

3. Weighted Graph Adjacency List

3.Adjacency Multilist
 Modified version of a adjacency lists.
 Edge-based rather than a vertex-based representation of graphs.

Node structure of adjacency multi list

OR
M -> A single bit field to indicate whether the edge has beeb examined or not.
Vi -> AVertex in the graph that is connected to vertex Vj by an edge.
Vj -> A Vertex in the graph that is connected to vertex Vi by an edge.
Link i for Vi or (Link1) -> A link that points to another node that has an edge incident on Vj.
Link j for Vi or (Link2) -> A link that points to another node that has an edge incident on Vi.

----------------------------------

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

Graph Traversal
In simple words, traversal means the process of visiting every node in the graph. There are 2
standard methods of graph traversal Breadth-First Search and Depth First Search.

1.Breadth First Search


Breadth-First Search (BFS) is a graph traversal algorithm, where we start from a selected(source)
node and traverse the graph level by level, by exploring the neighbor nodes at each level.
BFS algorithm
1.Visit the starting vertes and make it as visited.
{
 Display the vertex
 Set a pointer to the starting vertex[Currently working vertex]
}
2.If (Currently working vertex has adjacent unvisited vertex) then
{
 Visit the adjacent univisited vertex and make it as visited.
 Insert it into a queue.
 Display it.
}
Else
{
 Increment the pointer element to the queue.
 Remove the previous element from the queue.(Dequeue)
}
Repeat step-2 until Queue is empty.

BFS Routine

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

---------------------------------------
2.Depth First Search
 Depth First Search (DFS) is a graph traversal algorithm, where we start from a
selected(source) node and go into the depth of this node by recursively calling
the DFS function until no children are encountered.
 When the dead-end is reached, this algorithm backtracks and starts visiting the other
children of the current node.
DFS Algorithm
1.Put the starting vertex into the stack , mark it as visited.
 Display it
2.If (Stack[Top] has adjacent unvisited vertex) Then
{
 Visit the adjacent unvisited vertex and mark it as visited.
 Push it into the stack.
 Display it.
}
Else
{
 Pop the top element from the stack.(Back tracking)
}
Repeat Step-2 Until stack is empty.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

DFS Routine

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

-------------------------

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

Disjoint-Set
The Disjoint-set data structure is useful when we have a collection of items that are
divided into one or more pairwise disjoint sets (hence the name of the data structure), meaning
that no item is in more than one set. An example of this are the connected components of
an undirected graph, just like the one represented in the image below:

Here we have three connected components, or


equivalently, three disjoint sets.

If we are dealing with items, then is an array of size , and the th element of the
array represents the th item. More precisely, the th element of the array is the parent of the th
item. These relationships create one, or more, virtual trees. The following image to better
understand it.

This is the Find operation of the Disjoint-set data


structure, and can be implemented with the
following “c” code .
Find Operation
// Finds the representative of the set that i is an element
of
int find(int i)
{
while (p[i]>=0)
{
i=p[i] ; //If i is the parent of itself
}
return i; //Then i is the representative of his set
}

There you can see that is under in the tree, because . Also note that and have
no parents, because parent[2]=-1 and parent[3]=-1 .
Each tree is a disjoint set. If two elements are in the same tree, then they are in the same disjoint
set. The root node (or the topmost node) of each tree is called the representative of the set. There is
always a single unique representative of each set.
If is not the representative of his set, then it can be found by traveling up the tree until we find
the representative.

Union Operation
the Union operation is simple to implement. It takes, as input, two elements, finds the
representatives of their sets using the Find operation, and finally puts either one of the trees
(representing the set) under the root node of the other tree, effectively merging the trees and the

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

sets. If we would call Union on the two trees in the image example above, the result would be the
following:

2. Union Operation:
//merging or join two disjoint sets
int union(int i,int j)
{
parent[j]=i;
}

---------------------------------

Minimum Spanning Tree or Minimum Weight Spanning Tree

Minimum spanning tree can be defined as the spanning tree in which the sum
of the weights of the edge is minimum. The weight of the spanning tree is the
sum of the weights given to the edges of the spanning tree.

The minimum spanning tree is a spanning tree whose sum of the edges is
minimum.

Note:-
1.Weight of the edges should be minimum
2.Don’t form a cycle

Prim’s Algorithm-
Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the
subset of the edges of that graph which
 form a tree that includes every vertex
 has the minimum sum of weights among all the trees that can be formed from the graph

Steps:
1. Select a starting vertex
2. Repeat Steps 3 and 4 until there are fringe vertices
3. Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
4. Add the selected edge and the vertex to the minimum spanning tree T
5. EXIT

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

Example

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

Kruskal’s Algorithm-
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds
the subset of the edges of that graph which
 form a tree that includes every vertex
 has the minimum sum of weights among all the trees that can be formed from the graph
Steps
1. Sort all the edges from low weight to high weight.
2. Take the edge with the lowest weight and use it to connect the vertices of graph.
If adding an edge creates a cycle, then reject that edge and go for the next
least weight edge.
3. Keep adding edges until all the vertices are connected and a Minimum Spanning
Tree (MST) is obtained.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Unit - 5 Data Structures and Algorithms

***************

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Question Bank

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit – 1
Part –A
1. Define Data Structures.
A data structure is a method for organizing and storing data which would allow
efficient data retrieval and usage.
A data structure is a way of organizing data that considers not only the items
stored, but also their relationships to each other.

2. Why do we need data structures?


 Data structures allow us to achieve an important goal: component reuse.
 Once data structure has been implemented, it can be used again and
againin various applications.

3. List some common data structures.


a. Stacks
b. Queues
c. Lists
d. Trees
e. Graphs
f. Tables

4. How data structures are classified?


Data structures are classified into two categories based on how the data
itemsare operated:
i. Primitive data structure
ii. Non-Primitive data structure
 Linear data structure
 Non-linear data structure

5. Define primary data structures


Primary data structures are the basic data structures that directly operate upon the
machine instructions. All the basic constants (integers, floating-point numbers, character
constants, string constants) and pointers are considered as primary data structures.

6. Define static data structures.


A data structure formed when the number of data items are known in advance is
referred as static data structure or fixed size data structure.

7. List some of the static data structures in C.


Some of the static data structures in C are arrays, pointers, structures etc.

8. Define dynamic data structures.


A data structure formed when the number of data items are not known in advance is
known as dynamic data structure or variable size data structure.

9. List some of the dynamic data structures.


Some of the dynamic data structures in C are linked lists, stacks, queues, trees etc.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

10. Define linear data structures.


Linear data structures are data structures having a linear relationship between its
adjacent elements. Eg: Linked lists

11. Define non-linear data structures.


Non-linear data structures are data structures that don’t have a linear relationship
between its adjacent elements but have a hierarchical relationship between the elements.
Eg:Trees and Graphs.

12. Differentiate linear and non-linear data structure.


Sl.No Linear data structure Non-linear data structure
1 Data are arranged in linear or sequential Data are not arranged in linear
manner manner.
2 Every items is related to its previous and Every item is attached with many other
next item items
3 Data items can be traversed in a Data items cannot be traversed in a
single run. single run.
4 Implementation is easy Implementation is difficult.
5 Example: array, stack, queue, linked list Example: tree, graph

13. Define ADT (Abstract Data Type)


An abstract data type (ADT) is a set of operations and mathematical abstractions,
which can be viewed as how the set of operations is implemented. Objects like lists, sets
and graphs, along with their operation, can be viewed as abstract data types, just as
integers, realnumbers and Booleans.

14. Mention the features of ADT.


a. Modularity
i. Divide program into small functions
ii. Easy to debug and maintain
iii. Easy to modify
b. Reuse
i. Define some operations only once and reuse them in future
c. Easy to change the implementation

15. Difference between Abstract Data Type, Data Type and Data Structure.
 An Abstract data type is the specification of the data type which specifies
the logical and mathematical model of the data type.
 A data type is the implementation of an abstract data type. Data type has
its root in the abstract data type and a data structure comprises a set of
computer variables of same or different data types
 Data structure refers to the collection of computer variables that are
connected in some specific manner.

16. What are the two main classification of sorting based on the source of data?
According to the source of data sorting is classified into, a.External sorting b.Internal
sorting

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

17. What are the various factors to be considered in deciding a sorting algorithm?
Factors to be considered in deciding a sorting algorithm are,
a.Programming time
b.Executing time for program
c.Memory or auxiliary space needed for the programs environment

18. What is the purpose of quick sort?


The purpose of quick sort is to move a data item in the correct direction, just enough for it
to reach its final place in the array.

19. What is the advantage of quick sort?


Quick sort reduces unnecessary swaps and to moves an item to a greater distance in
one move.

20. Is the heap sort always better than the quick sort?
No, the heap sort does not perform better than the quick sort. Only when array is
nearly sorted to begin with the heap sort algorithm gains an advantage. In such a
case, the quick deteriorates to its worst performance of O (n2).

21. When is a sorting method said to be stable?


A sorting method is said to be stable if two data items of matching value are
guarantee to be not rearranged with respect to each other as the algorithm
progresses.

22. What is the worst-case complexity of insertion sort?


Worst-case complexity of insertion sort is, W (n) = n(n-1)/2 = O(n2) 15. What is
the average behavior of insertion sort? Average behavior of insertion sort is, A(n) =
n2/4 =O(n2)

23. What is the worst-case behavior of quick sort?


Worst-case behavior of quick sort is, W (n) = n(n-1)/2 = O(n2)

24. How does the bubble sort differ from the selection sort?
In selection sort, we find the smallest record and then perform an interchange.
Whereas in bubble sort, two records are interchanged immediately upon
discovering that they are out of order.

25. What is the main idea behind the selection sort?


The main idea behind the selection sort is to find the smallest entry among in
a(j),a(j+1),........a(n) and then interchange it with a(j). This process is then repeated
for each value of j.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit - 1
Part – B

1) What is the best time complexity of bubble sort? Example with its implementation?
2) Explain in detail about sorting and different types of sorting techniques
3) 3 Write a program to explain insertion sort . Which type of technique does it
belong.(or)Write a C-program for sorting integers in ascending order using insertion sort.
4) Solve the insertion sort results for each insertion for the following initial array of elements.
25, 6, 15,12 ,8 ,34,9 ,18 ,2
5) Demonstrate the selection sort results for each pass for the following initial array of
elements. 21, 6, 3, 57 ,13, 9, 14 ,18, 2
6) Explain the algorithm for QUICK sort (partition exchange sort) and give a suitable
example
7) Explain the algorithm for Merge sort and give a suitable example.
8) Write a program to implement Quick sort
9) Write a program to implement Merge sort.
10) Explain a sorting technique which follows divide and conquer mechanism with an
example. (quick & merge sorts)
11) Write and explain linear search procedure or algorithm with a suitable example.
12) Formulate recursive algorithm for binary search with its timing analysis.
13) Write a C program that searches a value in a stored array using linear search.
14) Write a program for recursive binary search to find the given element within array. For
What data binary search is not applicable?
15) Write a C program that searches a value in a stored array using non recursive binary
search
16) Define a data structure. What are the different types of data structures? Explain each of
them with suitable example.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit – 2
Part –A
1. Define Stack.
Stack is an ordered collection of elements in which insertions and deletions are
restrictedto one end. The end from which elements are added and/or removed is referred
to as top of the stack. Stacks are also referred as piles, push-down lists and last-in-first-
out (LIFO) lists.

2. What are the operations of the stack?


a. Create Stack/ Init Stack(Stack) – creates an empty stack
b. Push(Item) – pushes an item on the top of the stack
c. Pop(Item) – removes the top most element from the stack
d. Top(Stack) – returns the first element from the stack
e. Is Empty(Stack) – returns true if the stack is empty

3. How the operations performed on linked list implementation of stack?


a. Push and pop operations at the head of the list
b. New nodes should be inserted at the front of the list, so that they become
the topof the stack
c. Nodes are removed from the front(top) of the stack

4. What are the applications of stack?


The following are the applications of stacks
 Evaluating arithmetic expressions
 Balancing the parenthesis
 Towers of Hanoi
 Function calls
 Tree traversal

5. What are the methods to implement stack in C?


The methods to implement stacks are :
 Array based
 Linked list based

6. List out the basic operations that can be performed on a stack.


The basic operations that can be performed on a stack are
1. Push operation
2. Pop operation
3. Empty check
4. Fully occupied check

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

7. How the stack is implemented by linked list?


It involves dynamically allocating memory space at run time while performing stack
operations. Since it consumes only that much amount of space is required for holding
its data elements , it prevents wastage of memory space.
struct stack
{
int element;
struct stack *next
}*top;

8. State the different ways of representing expressions.


The different ways of representing expressions are
 Infix Notation
 Prefix Notation
 Postfix Notation

9. What are Infix, prefix, Postfix notations?


a. Infix notation
X + Y – Operators are written in-between their operands. This is the usual way
wewrite expressions. An expression such as

A * (B + C) / D

b. Postfix notation (also known as “Reverse Polish notation”)


X Y + Operators are written after their operands. The infix expression given
above isequivalent to

A B C + * D/

c. Prefix notation (also known as “Polish notation”)


+ X Y Operators are written before their operands. The expressions given
aboveare equivalent to

/*A+BCD

10. State the advantages of using infix notations.


 It is the mathematical way of representing the expression
 It is easier to see visually which operation is done from first to last

11. State the advantages of using postfix notations.


 Need not worry about the rules of precedence
 Need not worry about the rules for right to left associatively
 Need not need parenthesis to override the above rules

12. State the rules to be followed during infix to postfix conversions.


Fully parenthesize the expression starting from left to right. During parenthesizing,
the operators having higher precedence are first parenthesized

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

 Move the operators one by one to their right, such that each operator replaces
their corresponding right parenthesis
 The part of the expression, which has been converted into postfix is to be
treated assingle operand

13. State the rules to be followed during infix to prefix conversions.


 Fully parenthesize the expression starting from left to right. During
parenthesizing, the operators having higher precedence are first parenthesized
 Move the operators one by one to their left, such that each operator replaces
their corresponding left parenthesis
 The part of the expression, which has been converted into prefix is to be
treated assingle operand
 Once the expression is converted into prefix form, remove all parenthesis

14. Define queue.


It is a linear data structure that maintains a list of elements such that insertion
happens at rear end and deletion happens at front end.FIFO – First In First Out
principle

15. What is a Queue, how it is different from stack and how is it implemented?
Queue is a linear structure which follows the order is First in First out (FIFO) to
access elements.

16. What are the operations of a queue?


The operations of a queue are
 isEmpty()
 isFull()
 insert()
 delete()
 display()

17. How to implement a stack using queue?


A stack can be implemented using two queues. Let stack to be implemented be
‘s’ and queues used to implement be ‘q1’ and ‘q2’. Stack‘s’ can be implemented in two
ways:
 Method 1 (By making push operation costly)
 Method 2 (By making pop operation costly)

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

18. How to implement a queue using stack?


A queue can be implemented using two stacks. Let queue to be implemented be q
andstacks used to implement q be stack1 and stack2. q can be implemented in two ways:
 Method 1 (By making enQueue operation costly)
 Method 2 (By making deQueue operation costly)

19. Define a priority queue and how it is implemented.


Priority queue is a collection of elements, each containing a key referred as the
priority for that element. Elements can be inserted in any order (i.e., of alternating
priority), but are arranged in order of their priority value in the queue. The elements are
deleted from the queue in the order of their priority (i.e., the elements with the highest
priority is deleted first). The elements with the same priority are given equal importance
and processed accordingly.

20. What are the types of queues?


a. Linear Queues – The queue has two ends, the front end and the rear end. The
rear end is where we insert elements and front end is where we delete elements.
We can traverse in a linear queue in only one direction ie) from front to rear.
b. Circular Queues – Another form of linear queue in which the last position is
connected to the first position of the list. The circular queue is similar to linear
queue has two ends, the front end and the rear end. The rear end is where we
insert elements and front end is where we delete elements. We can traverse in a
circular queue in only one direction ie) from front to rear.

21. List the applications of queues.


 Jobs submitted to printer
 Real life line
 Calls to large companies
 Access to limited resources in Universities
 Accessing files from file server

22. Define circular queue.


A Circular queue is a queue whose start and end locations are logically connected
witheach other. That means the start location comes after the end location.

23. What are push and pop operations?


 Push – adding an element to the top of stack
 Pop – removing or deleting an element from the top of stack

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

24. What are enqueue and dequeue operations? (Nov/Dec 2014)(April/May 2016)(R)
 Enqueue - adding an element to the queue at the rear end
 Dequeue – removing or deleting an element from the queue at
thefront end

Unit - 2
Part – B

1) What is a Stack? Explain with example?


2) Explain any one applications of Stack with a example.
3) How an arithmetic expressions is evaluated using stacks. Explain with an example.
4) Write the algorithm for converting infix expression to postfix expression?
5) Write the algorithm for Push and pop operation in stack using linked list.
6) Explain queue ADT with its various operations.
7) Explain the applications of queues with an example.
8) Explain circular queue and its implementation with diagrammatic representation.
9) Write the procedure to convert the infix expression and steps involved in evaluating the
postfix expression. Convert the expression A-(B/C+(D%E*F)/G)*H to postfix form.
Evaluate the given postfix expression 9 3 4 * 8 + 4 / -.
10) What are circular queues. Write the procedure to insert an element to circular quque and
delete an element from a circular queue using array implementation.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit – 3
Part –A
1. Define List ADT
A list is a sequence of zero or more elements of a given type. The list is represented
as sequence of elements separated by comma. A1, A2, A3…..AN Where N>0 and
A is of type element.

2. Define Linked Lists


Linked list consists of a series of structures, which are not necessarily adjacent in
memory. Each structure contains the element and a pointer to a structure containing
its successor. We call this the Pointer. The last cell’s pointer points to NULL.

3. What are the ways of implementing linked list?


The list can be implemented in the following ways:
i. Array implementation
ii. Linked-list implementation
iii. Cursor implementation

4. What are the types of linked lists?


There are three types
i. Singly linked list
ii. Doubly linked list
iii. Circularly linked list
iv. Doubly Circular Linked list

5. How the singly linked lists can be represented?

6. How the doubly linked list can be represented?

Doubly linked list is a collection of nodes where nodes are connected by forwarded and backward
link. Each node has three fields:
 Address of previous node
 Data
 Address of next node.

7. What are benefits of ADT?


a. Code is easier to understand
b. Implementation of ADT can be changed without requiring changes to the program
that uses the ADT

8. When singly linked list can be represented as circular linked list?


In a singly linked list, all the nodes are connected with forward links to the next nodes in
the list. The last node has a next field, NULL. In order to implement the circularly linked
lists from singly linked lists, the last node’s next field is connected to the first node

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

9. When doubly linked list can be represented as circular linked list?


In a doubly linked list, all nodes are connected with forward and backward links to
the next and previous nodes respectively. In order to implement circular linked lists
from doubly linked lists, the first node’s previous field is connected to the last node
and the last node’s next field is connected to the first node.

10. List down the applications of List.


a. Representation of polynomial ADT
b. Used in radix and bubble sorting
c. In a FAT file system, the metadata of a large file is organized as a linked list of
FAT entries.
d. Simple memory allocators use a free list of unused memory regions, basically a
linked list with the list pointer inside the free memory itself.

11) What are the advantages of linked list?


a. Save memory space and easy to maintain
b. It is possible to retrieve the element at a particular index
c. It is possible to traverse the list in the order of increasing index.
d. It is possible to change the element at a particular index to a different value,
without affecting any other elements.

12) Mention the demerits of linked list.


a. It is not possible to go backwards through the list
b. Unable to jump to the beginning of list from the end.

13) What are the operations performed in list?


The following operations can be performed on a list are
1. Insertion
Insert at Start
Insert at End
Insert at Mid
2. Deletion
Delete at Start
Delete at End
Delete at Mid
3. Display

14) What are the merits and demerits of array implementation of lists?
Merits:
1. Fast, random access of elements
2. Memory efficient – very less amount of memory is required Demerits.
3. Insertion and deletion operations are very slow since the elements should be moved.
4. Redundant memory space – difficult to estimate the size of array.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

15) What is a circular linked list?


A circular linked list is a special type of linked list that supports traversing from the end of the
list to the beginning by making the last node point back to the head of the list.

16) List the basic operations carried out in a linked list.


The basic operations carried out in a linked list include:
1. Creation of a list
2. Insertion of a node
3. Deletion of a node
4. Modification of a node
5. Traversal of the list

17) List out the advantages of using a linked list.


It is not necessary to specify the number of elements in a linked list during its declaration
Linked list can grow and shrink in size depending upon the insertion and deletion that
occurs in the list Insertions and deletions at any place in a list can be handled easily and
efficiently. A linked list does not waste any memory space

18) State the difference between arrays and linked lists.


Basis For
Array Linked List
Comparison
Basic It is a consistent set of a It is an ordered set consisting of
fixed number of data items. a variable number of data items.
Size Specified during declaration. No need to specify; grow and
shrink during execution.
Storage Element location is allocated Element position is assigned
Allocation during compile time. during run time.
Order of the Stored consecutively Stored randomly
elements
Accessing the element Direct or randomly accessed, i.e., Sequentially accessed, i.e., Traverse
Specify the array index starting from the first
or subscript. node in the list by the pointer.
Insertion and deletion of Slow relatively as shifting is Easier, fast and efficient.
element required.
Searching Binary search and linear linear search
search
Memory required Less More
Memory Ineffective Efficient
Utilization

19) List out the applications of a linked list.


Some of the important applications of linked lists are manipulation of polynomials, sparse
matrices, stacks and queues.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

20) List out the disadvantages of using a linked list.


Searching a particular element in a list is difficult and time consuming. A linked list will use
more storage space than an array to store the same number of elements.

21) Difference between Singly Linked List, Doubly Linked List and Circular Linked List

S.No Parameter SLL DLL CLL


Pointers contains
Pointer can or cannot
Pointers contains the the address of
contains the address of
1 Address address of next in the next node as well
previous node as it depends
list as previous node
on type of circular linked list
in the list
Last element is
Last element is linked The last element is linked to
2 Connection linked to a null
to a null object the first element
object
3 No of pointer One pointers Two pointers Can have one or two pointers
The next node
Each node(item) of The last node knows about
Link to other also knows about
4 the list is connected to the first node and first node
node the previous
the next node. knows about the last node
node.
We can move We can or cannot move in
We can move in backward as well backward direction as it
5 Mobility
backward direction as forward depends on type of circular
direction linked list
Insertion In Two address need to Four address need Two or four address need to
6
between be updated to be updated be updated

Unit - 3
Part – B

1. Explain the various operations of the list ADT with examples


2. Write the program for array implementation of lists.
3. Write a C program for linked list implementation of list.
4. Explain the operations of singly linked lists.
5. Explain the operations of doubly linked lists.
6. Explain the steps involved in insertion and deletion into a singly and doubly linked
list.
7. What are the various operations on array. Write the procedure to insert an element
in the middle of the array.
8. What are the ways to insert a node in the linked list? Write an algorithm to insert a
node before a given node in the
9. What are the applications of Linked list in dynamic storage Management?

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit – 4
Part –A
1. Define tree.
Trees are non-liner data structure, which is used to store data items in a
shorted sequence. It represents any hierarchical relationship between any data Item.
It is a collection of nodes, which has a distinguish node called the root and zero or
more nonempty sub trees T1, T2,….Tk. each of which are connected by a directed
edge fromthe root.

2. Define the terms Edge and path of a tree.


 Edge is a connection between one node to another.

An example of edge is shown above between A and B. Basically, an edge is a line


between two nodes, or a node and a leaf.
 Path is a sequence of nodes and edges connecting a node with a descendant.

A path starts from a node and ends at another node or a leaf.


 A path includes all nodes and all edges along the path, not just edges.
 The direction of a path is strictly from top to bottom and cannot be changed in
middle. In the diagram, we can't really talk about a path from B to F although B
is above F. Also there will be no path starting from a leaf or from a child node to
a parent node.

3. How will you find the height of a tree?


The height of a node is the number of edges on the longest downward path
betweenthat node and a leaf.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

 Every node has height. So B can have height, so does A, C and D.


 Leaf cannot have height as there will be no path starting from a leaf.
 It is the longest path from the node to a leaf. So A's height is the number of edges of
thepath to E, NOT to G. And its height is 3.
 The height of a tree is the number of edges on the longest downward path between the
rootand a leaf.
Note:
 The height of a tree is the height of its root.
 The height of the root is 1.

4. How the depth of a tree is calculated?


The depth of a node is the number of edges from the node to the tree's root node.

Note - the depth of the root is 0.

5. Define level of a tree.

The level of a node is defined by 1 + the number of connections between the node and the
root. Note: level is depth plus 1.

6. Define Terminal node or leaf?


Nodes with no children are known as leaves. A leaf will always have degree zero
and is also called as terminal node.

7. Define Non-terminal node?


Any node except the root node whose degree is a non-zero value is called as a non-
terminal node. Non-terminal nodes are the intermediate nodes in traversing the given
tree from its root node to the terminal node.

8. Define sibling?
Nodes with the same parent are called siblings.

9. Define binary tree?


A Binary tree is a finite set of data items which is either empty or consists of a single item
called root and two disjoin binary trees called left sub tree max degree of any node is two.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

10. Define AVL tree?

AVL tree also called as height balanced tree .It is a height balanced tree in which every
node will have a balancing factor of –1, 0, and 1.Balancing factor of a node is given by
the difference between the height of the left sub tree and the height of the right sub tree.

11. What are the various operation performed in the binary search tree?
 insertion
 deletion
 find
 find min
 find max

12. What are the various transformation performed in AVL tree?


1. Single rotation
 Single L rotation
 Single R rotation
2. Double rotation
• LR rotation
• RL rotation

13. Define a full binary tree.


A full binary tree is a tree in which all the leaves are on the same level and every non-
leafnode has exactly two children.

14. Define a complete binary tree.


A complete binary tree is a tree in which
every non-leaf node has exactly two
children not necessarily to be on the same
level.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

15. Define a right-skewed binary tree.


A right-skewed binary tree is a tree, which has only right child nodes.

16. State the properties of a binary tree.


The maximum number of nodes on level n of a binary tree is 2n-1, where n≥1. The
maximum number of nodes in a binary tree of height n is 2n-1, where n≥1. For any non-
empty tree, nl=nd+1 where nl is the number of leaf nodes and nd is the number of nodes
of degree 2.

17. What is meant by binary tree traversal?


Traversing a binary tree means moving through all the nodes in the binary tree, visiting
eachnode in the tree only once.

18. What are the different binary tree traversal techniques?


 Preorder traversal
 Inorder traversal
 Postorder traversal

19. What are the tasks performed while traversing a binary tree?
 Visiting a node
 Traverse the left sub-tree
 Traverse the right sub-tree

20. What are the tasks performed during pre-order traversal?


 Process the root node
 Traverse the left sub-tree
 Traverse the right sub-tree

21. What are the tasks performed during in-order traversal?


 Traverse the left sub-tree
 Process the root node
 Traverse the right sub-tree

22. What are the tasks performed during post-order traversal?


 Traverse the left sub-tree
 Traverse the right sub-tree
 Process the root node

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

23. State the merits of linear representation of binary trees.


Storage method is easy and can be easily implemented in arrays. When the
location of a parent/child node is known, other one can be determined easily. It requires
static memory allocation so it is easily implemented in all programming language

24. State the demerit of linear representation of binary trees.


Insertions and deletions in a node take an excessive amount of processing time
due to data movement up and down the array.

25. State the merit of linked representation of binary trees.


Insertions and deletions in a node involve no data movement except the
rearrangement of pointers, hence less processing time.

26. State the demerits of linked representation of binary trees.


Given a node structure, it is difficult to determine its parent node. Memory
spaces are wasted for storing null pointers for the nodes, which have one or no sub-trees.
It requires dynamic memory allocation, which is not possible in some programming
language.

27. Define a binary search tree.


A binary search tree is a special binary tree, which is either empty or it should
satisfy the following characteristics: Every node has a value and no two nodes should
have the same value i.e) the values in the binary search tree are distinct. The values in
any left sub-tree are less than the value of its parent node. The values in any right sub-
tree are greater than the value of its parent node. The left and right sub-trees of each
node are again binary search trees.

28. What do you mean by general trees?


General tree is a tree with nodes having any number of children.

29. Define ancestor and descendant.


If there is a path from node n1 to n2, then n1 is the ancestor of n2 and n2 is the
descendant of n1.

30. Why it is said that searching a node in a binary search tree is efficient than that of a
simple binary tree?
In binary search tree, the nodes are arranged in such a way that the left node is having
less data value than root node value and the right nodes are having larger value than that
of root. Because of this while searching any node the value of the target node will be
compared withthe parent node and accordingly either left sub branch or right sub branch
will be searched. So, one has to compare only particular branches. Thus searching
becomes efficient.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

31. What is the use of threaded binary tree?


A binary tree is made threaded by making all right child pointers that would normally be
NULL point to the in-order successor of the node (if it exists). The threads are also
useful for fast accessing ancestors of a node.
There are two types of threaded binary tree. They
are:
1. Single Threaded
2. Double threaded

32. What is binary heap?


A binary heap is a complete binary tree which satisfies the heap ordering property. The
ordering can be one of two types:
 The min-heap property: the value of each node is greater than or equal to the
valueof its parent, with the minimum-value element at the root.
 The max-heap property: the value of each node is less than or equal to the
value ofits parent, with the maximum-value element at the root.

33. What is B-Tree? Write its Properties?


Tree is a self-balancing search tree. In most of the other self-balancing search trees. It is
assumed that everything is in main memory. The main idea of using B-Trees is to reduce
the number of disk accesses. Most of the tree operations (search, insert, delete, max, min,
etc) require O(h) disk accesses where h is height of the tree. B-tree is a fat tree. Height
of B- Trees is kept low by putting maximum possible keys in a B-Tree node. Generally,
a B-Tree node size is kept equal to the disk block size. Since h is low for B-Tree, total

disk accesses for most of the operations are reduced significantly compared to balanced
Binary Search Trees like AVL Tree, Red Black Tree.

34. What are the properties of B-Tree?


 All leaves are at same level. A B-Tree is defined by the term minimum
degree‘t’. The value of t depends upon disk block size.
 Every node except root must contain at least t-1 keys. Root may contain

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

minimum 1key. All nodes (including root) may contain at most 2t – 1 keys.
 Number of children of a node is equal to the number of keys in it plus 1.
 All keys of a node are sorted in increasing order. The child between two keys k1
and k2 contains all keys in range from k1 and k2.
 B-Tree grows and shrinks from root which is unlike Binary Search Tree.
BinarySearch Trees grow downward and also shrink from downward.
 Like other balanced Binary Search Trees, time complexity to search, insert
anddelete is O(Logn).

35. For the tree in the figure given below:


1. List the sibling of E
2. Give the height of the tree

36. Show the result of in order tree traversal from the figure given below

37. Define single threaded.


Where a NULL right pointers is made to point to the in-order successor (if successor
exists)

38. What are the applications of binary heap?


Heap sort , Selection algorithm, Graph algorithm, Priority queue, K-Way merge,
Order statistics

39. Define Double threaded.


Where both left and right NULL pointers are made to point to in-order predecessor and
in- order successor respectively. The predecessor threads are useful for reverse in-order
traversal & post-order traversal.

40. Applications of the Heap


Heap is used in the construction of priority queues. We can insert, delete, identify the highest
priority element, or insert and extract with priority, among other things, in O(log N) time
using apriority queue

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit - 4
Part – B
1) Write a c-program to implement binary search tree with an example
2) List the types of Binary Search Tree. Explain Insertion and Deletion Operation on Binary
Search Tree with Example.
3) Explain Tree Traversal with Example.
4) Create a Binary Search Tree for the following data and do in-order, Preorder and Post-
order traversal of the tree.50, 60, 25, 40, 30, 70, 35, 10, 55, 65, 5
5) What is the meaning of height balanced tree? How rebalancing is done in height balanced
tree
6) What is priority queue? Explain different types of priority queue with an example.
7) Define an AVL tree. Obtain an AVL tree by inserting one integer at a time in the following
sequence.150, 155, 160, 115, 110, 140, 120, 145, 130, 147, 170, 180.Show all the steps.
8) What is the difference between a binary tree and binary search tree, explain with an
example.
9) What is red black tree? Explain with an example?
10) What is splaying? Explain different types of splay trees?
11) What is B-tree? Insert the following elements into B-Tree 10,12,5,34,89, 4, 78,90.
[Order (m)=3]
12) Explain the different types of rotations in AVL trees with an example?
13) Explain Max Heap and Min Heap.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit – 5
Part –A
1. Define adjacent nodes.
Any two nodes which are connected by an edge in a graph are called adjacent nodes. For
example, if an edge x ε E is associated with a pair of nodes (u,v) where u, v ε V, then we
say that the edge x connects the nodes u and v.

2. What is a directed graph?


A graph in which every edge is directed is called a directed graph.

3. What is an undirected graph?


A graph in which every edge is undirected is called a directed graph.

4. What is a loop?
An edge of a graph which connects to itself is called a loop or sling.

5. What is a simple graph?


A simple graph is a graph, which has not more than one edge between a pair of
nodes than such a graph is called a simple graph.

6. What is a weighted graph?


A graph in which weights are assigned to every edge is called a weighted graph.
A weighted graph can be directed or non-directed

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

7. Define outdegree and indegree of a graph?


For a directed graph G=(V(G),E(G)), the Out-Degree Sequence is a sequence obtained by
ordering the out-degrees of all vertices in V(G) in increasing order. The In-Degree
Sequence is a sequence obtained by ordering the in-degrees of all vertices in V(G) in
increasing order.

From the graph earlier, the out-degree sequence (blue degrees) is (0,1,1,1,2,3), while the
in- degree sequence (red degrees) is (0,1,1,2,2,2).

8. Define path in a graph?


The path in a graph is the route taken to reach terminal node from a starting node.

9. What is a simple path?


A path in a diagram in which the edges are distinct is called a simple path. It is also called as edge
simple.

10. What is a cycle or a circuit?


A path which originates and ends in the same node is called a cycle or circuit.

11. What is an acyclic graph?


A simple diagram which does not have any cycles is called an acyclic graph.

12. What is meant by strongly connected in a graph?


A directed graph is strongly connected if there is a path between all pairs of vertices. A strongly
connected component (SCC) of a directed graph is a maximal strongly connected subgraph.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

13. When is a graph said to be weakly connected?


When a directed graph is not strongly connected but the underlying graph is connected,
then the graph is said to be weakly connected.

14. What is an undirected acyclic graph?


When every edge in an acyclic graph is undirected, it is called an undirected acyclic graph.
It is also called as undirected forest.

15. What are the two traversal strategies used in traversing a graph?
a. Breadth first search
b. Depth first search

16. What is a minimum spanning tree?


A minimum spanning tree of an undirected graph G is a tree formed from graph edges that
connects all the vertices of G at the lowest total cost.

17. What do you mean by breadth first search (BFS)?


BFS performs simultaneous explorations starting from a common point and spreading out
independently.

18. Differentiate BFS and DFS.


Sl.No. DFS BFS
1. Backtracking is possible from a Backtracking is not possible
dead end
2. Vertices from which exploration is The vertices to be explored are
incomplete are processed in a organized as a
3. Search is done in one particular The vertices in the same level are
direction maintained

19. Define adjacency list.


Adjacency list is an array indexed by vertex number containing linked lists. Each node Vi the ith
array entry contains a list with information on all edges of G that leave Vi. It is used to represent
the graph related problems.

20. List some of the applications of graph.


 Social network graphs
 Transportation networks
 Job scheduling

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

 Aircraft scheduling
 Bi-processor tasks
 Pre-colouring extension
 Time table scheduling
 Fingerprint reconstruction

21. What are the representations of graph?


The two commonly used representations of a graph are:
1. Adjacency Matrix
2. Adjacency List

22. Define Graph.


A graph G consist of a nonempty set V which is a set of nodes of the graph, a set E which
is the set of edges of the graph, and a mapping from the set for edge E to a set of pairs of
elements of V. It can also be represented as G=(V, E).

23. What do you mean by shortest path?


A path having minimum weight between two vertices is known as shortest path, in which
weight is always a positive number.

24. Name two algorithms two find minimum spanning tree.


 Kruskal’salgorithm
 Prim’s algorithm

25. Define graph traversals.


Traversing a graph is an efficient way to visit each vertex and edge exactly once.

26. List the two important key points of depth first search.
 If path exists from one node to another node, walk across the edge – exploring the
edge.
 If path does not exist from one specific node to any other node, return to the
previous node where we have been before – backtracking.

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Question Bank Data Structures And Algorithms

Unit - 5
Part – B

1) Explain prims algorithm with an example


2) Explain Krushkal’s algorithm with an example
3) What is Graph? Explain matrix and linked list representation of a graph. Also give the
application of Graph.
4) Explain Breadth First Search traversal of Graph using an example.
5) Explain Depth First Search traversal of Graph using an example.
6) Construct the minimum spanning tree (MST) for the given graph using Kruskal’s and
Prim’s Algorithm

RADHAKRISHNAN.P, Assistant Professor, Department of CS & AI, SR University.


Previous Year Question Paper
SET - 2
Code No.: 20ES117
II B.TECH. I SEM. (R20) SUPPLEMENTARY EXAMINATIONS, JUNE – 2022
DATA STRUCTURES AND ALGORITHMS
(CSE, CSE(AI&ML)(CS)(DS))

Time: 3 Hours Max. Marks: 60


PART – A
Answer ALL questions
5x2
1. Which is the efficient sorting technique among insertion sort and selection sort? Justify your
answer.
2. What is the value of the postfix expression 6 3 2 4 + - * ?
3. List the advantages of doubly linked list over singly linked list.
4. In which of the binary tree, at each level L, the number of nodes are 2 L-1 ? Give an example.
5. Traverse the below given graph using DFS:

PART – B
Answer any FIVE questions
All questions carry equal marks
5 x 10
1. a) Write a C program to search key element in the list using binary search.
b) Apply selection sort to sort given elements in ascending order 7,4,2,1,9,3,8
2. a) What is stack overflow and underflow? Give examples.
b) What is the limitation of linear queue? How it is overcome using circular queue?
3. a) Design an algorithm to evaluate postfix expression using stack
b) Write C function to display circular queue using array.
4. a) Write the node structure of singly linked list (SLL). Develop a C function to count the number
of nodes in a SLL.
b) Write a C function to insert new element after the given position on doubly linked list.
5. a) Write a C function to display doubly linked list contents in reverse order.
b) Explain how circular linked list is different from singly linked list.
6. a) Define with examples the terms siblings, level and depth with respect to tree data structure.
b) What are threaded binary trees? List any 2 applications of it.
7. a) Define Binary Search Tree (BST). Construct a BST for the list 5,2,9,1,7,3.
b) What is the difference between binary tree and strictly binary tree? Give examples.
8. a) What is spanning tree? Write kuskal’s algorithm to generate spanning tree.
b) Differentiate breadth first search and depth first search with examples.
🙚*🙚
Code No.: 20ES117
II B.TECH. II SEM. (R20) REGULAR EXAMINATIONS, MAY – 2022
DATA STRUCTURES AND ALGORITHMS
(ECE, ECE[AIML, IOT])

Time: 3 Hours Max. Marks: 60


PART – A
Answer ALL questions
5x2
1. What is the best sorting algorithm? Why?
2. Discuss various operations of Stack ADT.
3. List advantages of linked list over arrays.
4. Differences between AVL tree and Binary search tree.
5. List out various graph traversal techniques.
PART – B
Answer any FIVE questions
All questions carry equal marks
5 x 10
1. What is Binary search algorithm? Illustrate with an example and find out its running time.
2. Perform Merge sort on the following elements by writing suitable algorithm:
14 18 17 13 24 16 29 25 39 43 33 28
3. Create a stack by linked list implementation. Read a list of integers and print them in reverse
order.
4. Describe about Circular queues and design an algorithm for insert an element in a particular
position of a Circular queues.
5. Describe about double linked list and write an algorithm for insert an element in a particular
position of a double linked list.
6. Describe various operations on Binary Search Tree (BST) with an examples.
7. What is AVL tree? Define Balance factor. Explain RR rotation with an example.
8. What is minimum-cost spanning tree problem? Explain with example Kruskal’s algorithm for
minimum-cost spanning tree.
🙚*🙚
Code No.: 20ES117
B.TECH. III SEM. (R20) REGULAR EXAMINATIONS, DECEMBER – 2021
DATA STRUCTURES AND ALGORITHMS
(CSE, CSE(AI&ML)(CS)(DS))

Time: 3 Hours Max. Marks: 60


PART – A
Answer ALL questions
5x2
1. Show the detailed contents of the stack to evaluate the given postfix expression.
{1 2 3 + * 3 2 1 - + *}
2. Define AVL tree? Give an example.
3. Write the application of sorting techniques.
4. What is a linked list? Write advantages of doubly linked list over the singly linked list.
5. Describe given two types of graphs: Directed and undirected graphs.

PART – B
Answer any FIVE questions
All questions carry equal marks
5 x 10
1. Explain how the stack is used to convert the following infix expression into postfix form
a/b-c+d*e-a*c and evaluate that postfix expression for given data a=6, b=3, c=1, d=2, e=4.
2. a) Show the result of inserting 3,1,4,6,9,2,5,7 into an initially empty binary search tree.
b) Define a stack? Write all the stack operations.
3. a) Construct a binary tree having the following traversal sequences:
Preorder traversal: A B C D E F G H I
Inorder traversal: B C A E D G H F I
b) Write a short note on Graph representation with suitable example.
4. Write the pseudo code to find a minimum spanning tree using Prim’s algorithm.
5. Draw the steps required to perform a single right rotation and double LR rotation in an AVL Tree.
6. Write an algorithm for Quick sort and differentiate Insertion sort, and Bubble sort.
7. Construct max heap for the following elements:
40, 80, 30, 20, 10, 40, 30, 60, 100, 70.
8. Write an algorithm to perform all delete operations on double linked list.

🙚*🙚

You might also like