Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
108 views

Data Structures and Algorithms in C

Uploaded by

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

Data Structures and Algorithms in C

Uploaded by

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

CAT II Portion

Unit II
Applications of Stack: Balancing Symbols, Postfix Expressions, Infix to
Postfix Conversion Queue ADT – array–based & linked list implementation
– Types of Queue – Applications of queues.
Unit III
Tree ADT – Representation – Traversals – Binary Tree
Expression trees
Binary Search Tree
AVL Trees (2 marks only)

1
19EC403 - Data Structures and
Algorithms in C

IV Semester B.E ECE ‘C’ (2022-2026 Batch)


Academic Year 2023 – 2024 (Even Semester)

Dr.J.Senthil Kumar
Associate Professor (Senior Grade)
Department of Electronics and Communication Engineering
Mepco Schlenk Engineering College (Autonomous), Sivakasi
senthilkumarj@mepcoeng.ac.in
Mini Project Review 1:
1) Mini Project Report Template 19/03/2024
http://surl.li/rfxkf Along with the filled mini project template,
Come with double / doubly circular linked list
2) Flow Diagram - Tool implementation of your
https://draw.io Problem statement.

3) Latex Documentation Tool (for CV, Reports and Article


Writing)
https://www.overleaf.com/
https://www.overleaf.com/learn/latex/
Learn_LaTeX_in_30_minutes
3
Assignment - 1 (Deadline:18/03/2024)
1) Implement singly circular linked list for implementation of the chosen
problem statement for your batch with nodes with multiple data and data
types that includes the following algorithms
▷ Insert
Also use file handling concept in C, to write the contents of
▷ Display the list to a .txt file. Write an algorithm to complete this task
▷ Modify as well.
Write the Worst case run-time of each algorithms
▷ Search
▷ Delete (based on value)
▷ Clear (make the list empty)
▷ Insert at beginning
▷ Insert at particular position
▷ Delete at Beginning
▷ Delete at End
▷ Delete at particular position
Assignment - 1 (Deadline: 18/03/2024)
2) Implement doubly circular linked list for implementation of the chosen
problem statement for your batch with nodes with multiple data and data types
that includes the following algorithms
▷ Insert Also use file handling concept in C, to write the contents of
▷ Display Forward the list to a .txt file. Write an algorithm to complete this task
as well.
▷ Display Backward
Write the Worst case run-time of each algorithms
▷ Modify
▷ Search Forward
▷ Search Backward
▷ Delete (based on value)
▷ Clear (make the list empty)
▷ Insert at beginning
▷ Insert at particular position
▷ Delete at Beginning
▷ Delete at End
▷ Delete at particular position
Assignment - 2 (Deadline: 08.04.2024)
https://www.hackerrank.com/domains/data-structures

Solve all the Data Structure


Algorithms listed under Basic
and Intermediate categories in
Hackerrank website using
either C / C++ Programming
Language only.

Every individual student


should send the updated status
(with their profile name) and
submit a printed copy as well.

6
Why Study Data Structures?


“Bad programmers worry about the code.
Good programmers worry about data
structures and their relationships.”
-Linus Torvalds
7
Course Objectives
▷ To study the design and applications of
linear ADTs such as List, Stack and Queue.
▷ To implement tree and graph based Non
Linear ADTs.
▷ To implement various sorting algorithms.

8
Course Outcomes
At the end of the course, the students will be able to
CO1. Analyze the running time of various algorithms.
CO2. Develop the various linear data structures such as List,
Stack and Queue ADTs.
CO3. Develop the various nonlinear data structures such as
Trees, Graphs.
CO4. Apply Hashing and Set concepts for real world
applications.
CO5. Implement sorting algorithms for different applications.
9
Concept Map of the Course

10
11
UNIT I - ALGORITHM ANALYSIS AND
LINEAR DATA STRUCTURES-LIST

Definition of an Algorithm – Mathematical preliminaries


- Running Time Calculations - Algorithm Complexity :
time and space complexity List ADT – Array–based &
Linked list implementation – singly linked lists- circularly
linked lists- doubly-linked lists – Polynomial
Manipulation using lists
12
UNIT II - LINEAR DATA STRUCTURES-
STACK AND QUEUE
Stack ADT – array–based & linked list
implementation – Applications of Stack:
Balancing Symbols, Postfix Expressions, Infix to
Postfix Conversion Queue ADT – array–based &
linked list implementation – Types of Queue –
Applications of queues 13
UNIT III - TREE DATA STRUCTURES

Tree ADT – Representation – Traversals


– Binary Tree – Expression trees –
Binary Search Tree – AVL Trees

14
UNIT IV - SET AND GRAPH

Disjoint Set ADT – dynamic equivalence problem –


smart union algorithms – path compression –
applications of Set Graph – Terminology and
Representations – Graph traversal Topological Sort
– Shortest Path Algorithm: Dijkstra’s Algorithm –
Minimum Spanning Tree – Prim's and Kruskal's
Algorithms 15
UNIT V - HASHING AND SORTING
ALGORITHMS

Hashing – Separate chaining – open


addressing – rehashing Sorting
Algorithms: Bubble Sort, Insertion
Sort, Merge Sort, Quick Sort.
16
Text Books

1. Mark Allan Weiss, "Data Structures


and Algorithm Analysis in C", 2nd Edition,
Pearson Education, 2005.
2. R. F. Gilberg, B. A. Forouzan, "Data
Structures: A Pseudocode Approach with
C", 2nd Edition, Thomson India Edition, 2005.

17
Mark Allan Weiss, "Data
Structures and Algorithm
Analysis in C", 2nd Edition,
Pearson Education, 2005.
Ebook link:
http://svslibrary.pbworks.com/f/Data+Structures+and+
Algorithm+Analysis+in+C+-+Mark+Allen+Weiss.pdf
Source Code of Algorithms in the Book:
http://users.cs.fiu.edu/~weiss/dsaa_c2e/files.html

18
R. F. Gilberg, B. A.
Forouzan, "Data Structures:
A Pseudocode Approach
with C", 2nd Edition, Thomson
India Edition, 2005.

Ebook link:
https://ebin.pub/download/data-structures-a-p
seudocode-approach-with-c-2nbsped-053439
0803-9780534390808.html

19
Data Structures Handbook

Android App:

https://play.google.com/store/a
pps/details?id=com.bashoverfl
ow.datastructures

Web Link:
https://www.thedshandbook.
com/

20
Other popular Android Apps

21
19EC452

Data Structures Laboratory

22
COURSE OBJECTIVES

▷ To develop programming skills in design


and implementation of linear data
structures.
▷ To work with trees, graphs with the
implementation of non-linear data
structures.
▷ To implement various sorting algorithms.
23
COURSE OUTCOMES
At the end of the course, the students will be able to
CO1. Develop the various linear data structures such
as List, Stack and Queue ADTs.
CO2. Improve programming skills in design and
implementation of nonlinear data structures.
CO3. Solve graph based applications.
CO4. Implement the concepts of Hashing and Sets
CO5. Implement sorting algorithms for different
applications.
24
List of Lab Experiments
1. List ADT Implementation using Array And Linked list
2. Stack Implementation Using Array And Linked Lists
3. Queue Implementation Using Array And Linked Lists
4. Binary Search Tree Implementation
5. AVL Tree Implementation
6. Disjoint-Set Implementation
7. Graph Traversal Implementation
8. Hashing and Hash function Implementation
9. Bubble Sort, Insertion Sort And Heap Sort
10.Merge Sort And Quicksort
11.Mini Project
25
UNIT - I

Algorithm Analysis and Linear


Data Structures - List

27
Unit - I
Algorithm Analysis and Linear Data Structures - List
● Algorithm
● Mathematical preliminaries on analysis.
● Run-time and space complexity analysis of algorithm
● Data Structures
● Abstract Data Type (ADT)
● List ADT (Data Structure)
○ Array based
○ Linked list based
■ Single Linked list
■ Doubly linked list
■ Circular linked list
28
1.C Prog to find product of 2 numbers

#include<stdio.h>
int main(){
int a,b,c;
printf("enter the numbers");
scanf("%d %d",&a,&b);
c=a*b;
printf("product=%d",c);
} 29
2.C Prog to find product of 2 numbers
using structure
#include<stdio.h>
struct product{
int a,b,c;
};
int main(){
struct product p; //structure variable
printf("Enter two numbers:");
scanf("%d %d",&p.a,&p.b);
p.c=p.a*p.b;
printf("Product:%d",p.c);
30
}
3.C Prog to find product of 2 numbers
using structure pointer
#include<stdio.h>
struct product{
int a,b,c;
};
int main(){
struct product *p; //structure pointer variable
p=(struct product *)malloc(sizeof(struct product)); //dynamic memory allocation
printf("Enter two numbers:");
scanf("%d %d", &p->a, &p->b);
p->c=p->a*p->b;
printf("Product:%d",p->c);
free(p); //free memory allocation
} 31
4.C Prog to find product of 2 numbers by passing a
structure to a function (Call by reference)
#include<stdio.h>
struct product{
int a,b,c;
};
void multiply(struct product *q){ //argument is structure pointer variable
q->c=q->a*q->b;
}
int main(){
struct product p;
printf("Enter two numbers:");
scanf("%d %d",&p.a,&p.b);
multiply(&p); //Call by reference
printf("Product:%d",p.c);
} 32
4.C Prog to find product of 2 numbers by passing a
structure to a function (Call by value)
#include<stdio.h>
struct product{
int a,b,c;
};
struct product multiply(struct product q){ //argument is struct , returns struct
q.c=q.a*q.b;
return q; //Returns the structure to main()
}
int main(){
struct product p;
printf("Enter two numbers:");
scanf("%d %d",&p.a,&p.b);
p=multiply(p); //Call by value
printf("Product:%d",p.c);
33
}
5.C Prog to find product of 2 numbers passing
structure pointer to a function
#include<stdio.h>
struct product{
int a,b,c;
};
void multiply(struct product *q){ //argument is structure pointer variable
q->c=q->a*q->b;
}
int main(){
struct product *p; //structure pointer variable
p=(struct product *)malloc(sizeof(struct product)); //dynamic memory allocation
printf("Enter two numbers:");
scanf("%d %d",&p->a,&p->b);
multiply(p); //function call with argument as pointer variable
alone
printf("Product:%d",p->c); 34
5.C Prog to find product of 2 numbers passing
structure pointer to a function (Return struct)
#include<stdio.h>
struct product{
int a,b,c;
};
struct product* multiply(struct product *q){ //argument is struct pointer, return struct pointer
q->c=q->a*q->b;
return q; //returning struct pointer
}
int main(){
struct product *p; //structure pointer variable
p=(struct product *)malloc(sizeof(struct product)); //dynamic memory allocation
printf("Enter two numbers:");
scanf("%d %d",&p->a,&p->b);
p=multiply(p); //argument is struct pointer variable alone, return struct pointer
printf("Product:%d",p->c);
free(p); 35
}
Homework - 30/01/2024

Write a C Program to implement the following structure as a pointer variable and pass
it to a function to get data and print the details in another function.

struct smartphone{
char brand[10];
char model[10];
int year;
float cost;
long int number;
}
36
Homework - 30/01/2024
#include<stdio.h>
struct smartphone{
char brand[10];
char model[10];
int year;
float cost;
long int number;
};
void getdetail(struct smartphone *p){
printf("Enter brand, model, year, cost, and number: ");
scanf("%s %s %d %f %ld", &p->brand, &p->model, &p->year, &p->cost, &p->number);
}
void display(struct smartphone *p){
printf("Brand:%s\n",p->brand);
printf("Model:%s\n",p->model);
printf("Year:%d\n",p->year);
printf("Cost:%f\n",p->cost);
printf("Number:%ld\n",p->number);
}
int main(){
struct smartphone *q;
q=(struct smartphone*)malloc(sizeof(struct smartphone));
getdetail(q);
display(q);
return 0; Code Courtesy
} Gauresh Kumar G
II ECE C 37
Introduction to Data
Structures

38
Unit - I
Algorithm Analysis and Linear Data Structures - List
● Algorithm
● Mathematical preliminaries on analysis.
● Run-time and space complexity analysis of algorithm
● Data Structures
● Abstract Data Type (ADT)
● List ADT (Data Structure)
○ Array based
○ Linked list based
■ Single Linked list
■ Doubly linked list
■ Circular linked list
39
Introduction to Data Structures
Data:
Sequence of bits, bytes, text, images, videos etc.,
Data Structure:
It provides a systematic way of organizing, accessing and
processing of data, present in the computer memory
Information:
If we arrange data in an appropriate sequence, then it forms
a structure and gives us a meaning. It is called as
information.
40
Introduction to Data Structures
Algorithm:
▷ Outlines the essence of computation procedures
through step by step instructions.
▷ In the context of data structure, algorithms are:
○ Meant to give proper structure to the data.
○ Extract information from the data
Program:
Implementation of the algorithms using appropriate
programming language like C, C++, Python, Java
etc.,
41
What is Data Structures?
▷ Data Structure is the representation of relationship
that exists between individual elements of data to
carry out certain operations / tasks.
▷ Data Structure considers not only the organization of
the elements, but also stores the relationship between
those elements.

42
What is Data Structures?
Data Structure = Data + Organizing, accessing
and processing of data (through algorithms)
Data Structure = Data + Establish relationship
between data (through algorithms)
Data Structure = Organized data + Allowed set
of operations on those data (Provided by the
algorithm)

43
Why Data Structures?
▷ Study of how data needs to be stored in computer,
so that operations on the data can be implemented
efficiently.
▷ Data structures are highly important, when we have
large amount of data.
▷ Conceptual and concrete means to organize data for
efficient storage and retrieval / manipulation.

44
Abstract Data Types (ADT)

45
Abstract Data Type (ADT)
▷ ADTs are more promising way of looking at data structures. They are
user defined data types. All data structures are built on top of ADTs.
▷ From the perspective of data structures, ADTs focuses on what it does
on does on data and it ignores how the tasks are done / implemented.
ADT = Interface + Implementation (through algorithms)
Interface - Properties of ADT and especially the operations that it supports.
Implementation - Representation of data structures and algorithm that
implements the operations

46
Interface vs Implementation (in class / structure)

struct student {
class student {
public:
};
void getdata(){}
};
int main(){
int main(){ struct student s;
student s; interface
getdata();
s.getdata();
implementation sort();
s.sort();
}
}
47
Benefits of Abstract Data Type (ADT)
▷ Code easy to understand
▷ Implementation of ADT can be changed, with the program
that already implements it.
ADT = Data + Operations bundled along
with it
(Ex: String - > Operations are finding length, concat, compare,
search etc.,)

48
ADT vs Data Structures
ADT - Tells only abstraction, not cares about
implementation. (Answers the question of what is implemented?)
Data Structures - (Answers the question of how it is implemented?)
▷ Specifies how you represent data, store them and
organize them.
▷ Gives you the ways for implementing the ADT
▷ It is done based on the algorithm defined on that
data.
49
Types of Data Structures

50
Types of Data Structures
▷ Primary / Primitive/ Built-in Data Structure
○ Basic constants / Data types (int, char, float, double)
○ Pointers
▷ Secondary /Non- Primitive/ User defined Data Structure
○ Static (Arrays, Structures)
○ Dynamic
■ Linear (Dynamic arrays, list, stack, queue)
■ Non-Linear (Tree, Graph, Disjoint set, Hashtable)

51
Types of Data Structures

Secondary /Non- Primitive/


Primary / Primitive/ Built- User defined Data Structure
in Data Structure

Static Dynamic
Basic constants /
Pointers
Data types

Arrays Structure Linear Non-linear


int
Dynamic
Trees
array
char
List Graphs
float
Hash
Stack
tables
double
Set
Queue
Union 52
53
Data Structures Visualizations

https://visualgo.net/en
https://www.cs.usfca.edu/~galles/visualization/Algorith
ms.html
https://www.toptal.com/developers/sorting-algorithms

54
Linear Data Structures
▷ A data structure is said to be linear, if the available elements
are arranged in a proper sequence (one after another).
▷ Any element / data / node in a linear data structure will have
maximum of only two neighbours. It can also have only one
neighbour as well.
Some of the common linear data structures are:
1) Array
2) List
3) Stack
4) Queue
55
Operations supported on Linear Data Structures
Algorithms written for the data structure will carry out the
intended operations on the data.
Few major operations supported on linear data structure are:
1) Traversal
2) Insertion
3) Search
4) Delete
5) Sorting
6) Merging
7) etc.,
56
List ADT

57
List ADT
1) General list of n items may be of form A1, A2….An
2) Elements in the list can be int, char, float, structure, or any
combination of any complex data type elements.
3) We can perform set of operations on the list to insert, delete, print
etc.,
4) List is a flexible data structure because, they can grow (insert) or
shrink (delete) based on the demand (data).
5) The elements can be accessed, inserted or deleted at any position
within the list. (for performing these operations, we need to write
algorithms)
58
Implementation of List ADT

Two ways of implementation (writing the algorithm


/ program ) is possible
1) Array based implementation
2) Linked list implementation (Pointer based
implementation)

59
Array of Structure Passed to Functions
#include<stdio.h>
struct smartphone {
char brand[10];
char model[10];
int year;
float cost;
long int number;
};
void getdetail(struct smartphone p[], int x) {
int i;
for(i = 0; i < x; i++) {
printf("Enter brand, model, year, cost, and number for smartphone %d: ", i + 1);
scanf("%s %s %d %f %ld", p[i].brand, p[i].model, &p[i].year, &p[i].cost, &p[i].number);
}
}
void display(struct smartphone p[], int x) {
int i;
for(i = 0; i < x; i++) {
printf("\nDetails of smartphone %d:\n", i + 1);
printf("Brand: %s\t", p[i].brand);
printf("Model: %s\t", p[i].model);
printf("Year: %d\t", p[i].year);
printf("Cost: %.2f\t", p[i].cost);
printf("Number: %ld\t", p[i].number);
}
} 60
Pointer to Structure Passed to Functions
#include<stdio.h>
struct smartphone{
char brand[10];
char model[10];
int year;
float cost;
long int number;
};
void getdetail(struct smartphone *p, int x) {
int i;
for (i = 0; i < x; i++) {
printf("Enter brand, model, year, cost, and number for smartphone %d: ", i + 1);
scanf("%s %s %d %f %ld", (p + i)->brand, (p + i)->model, &(p + i)->year, &(p + i)->cost, &(p + i)->number);
}
}
void display(struct smartphone *p, int x) {
int i;
for (i = 0; i < x; i++) {
printf("\nDetails of smartphone %d:\n", i + 1);
printf("Brand: %s\t", (p + i)->brand);
printf("Model: %s\t", (p + i)->model);
printf("Year: %d\t", (p + i)->year);
printf("Cost: %f\t", (p + i)->cost);
printf("Number: %ld\t", (p + i)->number);
}
}
int main() {
int n;
struct smartphone *q;
printf("Enter the number of smartphones: "); 61
scanf("%d", &n);
List ADT Implementation List ADT Implementation with
with Single data Example Multiple data Example
S.No. Name Brand Model Number

0 1. Ram Apple iphone 13 94655…


0
. 2. Arnold Oppo A74 96545…
. .
struct node{
. .
int Data; .
.
.
} s[60];
59 60. Suriya Samsung S24 98645…

struct mobile{
int Sno;
char Name[10];
char Brand[10];
char Model[10];
long int Number;
59 } s[60]; 62
node n
node 1 node 2 node 3

....
Head .

node 1 node 2 node 3 .... node n

Head
63
Homework - 31/01/2024

Write a C program to multiply two matrices using dynamic


memory allocation, by getting two matrices in a function
performing the multiplication in another function, and displaying
the result in yet another function. Pass the pointer matrices to
each function to perform the operations.

64
Array vs List
Features Array List

Size Fixed Can grow / shrink dynamically

Type of Homogeneous Heterogeneous


Elements

Memory Continuous Random


Allotment

Tracking of Need not keep track (since it We need to keep track of the memory
memory is continuous) location (since it is random)
locations

Speed of Faster (memory is Slower (memory is not continuous)


Accessing continuous)
elements

65
Array based List ADT vs Linked List
Features Array based List ADT Linked List (Pointer based)

Implementation Using arrays Using pointers

Memory allotment Continuous Random

Memory Access Random access Sequential access


mechanism (Ex:Digital mp3 music player) (Ex:Audio magnetic tapes )

Elements Proportional to size of array We can insert elements till the size of
fixed your RAM.

Cost of insertion and Proportional to size of array Independent on the size of the list (low)
deletion of elements (very high)

Running time and High Low


space requirement

Access Speed Faster Slower


66
Array-based Implementation
of List ADT

67
Array based implementation of List
ADT
▷ All operations (Algorithms) on list are
implementations are implemented using array
concepts.
▷ Either static or dynamic array can be implemented.
▷ But it is recommended to use dynamic arrays to
make the list ADT / data structures to be flexible
(grow / shrink the size of the list based on data
availability)
68
Advantages - Array based
implementation
▷ Random access to elements are possible
▷ Quick access to elements are enabled

Disadvantages - Array based implementation


▷ Requires overestimated memory space, which will be
wastes at run time. (char name[100];)
▷ Running time limitation will be there for certain / most
of the operations (Ex: insertion, deletion etc.,)- Very
high cost 69
Homework -01/02/2024

What are the core data structures used in the development of the
following platforms
1) Facebook - Graphs
2) Twitter - Graphs
3) LinkedIn - Graph, Lists
4) WhatsApp - Queue
5) Instagram
6) Google Maps - Graphs
7) Quora
70
Array based implementation of List ADT
Problem Statement / Aim / Objective
To implement the array based list ADT for a set of numbers (marks of students / set of integers / scores
by a individual players in certain number of innings). Write appropriate (following set of) algorithms for
handling the available data (set of numbers ) and to structure them (Data structure)
1) Insert
a) Insert at a particular location
b) Insert before / after a particular value
c) Insert at beginning
d) Insert at end etc.,
2) Display
3) Modify
Write a C program to implement the given problem statement with separate
4) Search functions for each algorithm.
5) Delete
a) Based on value
b) Based on location
c) Delete at beginning of list
d) Delete at end etc.,
6) Clear
7) etc.,
71
List Implementation with Single data
Example
0
#define MAX 60
struct node{
int data;
} s[MAX];
int top = -1; //initialize a reference to traverse across the array based list

MAX-1 72
C Program template for implementation
#include<stdio.h>
#define MAX 60 //defining the maximum size of array based list
int top = -1 //initialize a reference to traverse across the array based list
//list down all the function prototypes to be used in the implementation
void insert(int);
void display();
void deletedata(int); //pass data to be deleted
void modify(int, int); //pass old data and new data to be modified
int search(int); //pass value to be searched and get the location
etc.,etc.,
struct node{
int data;
} s[MAX]; 73
Algorithm for inserting into List ADT
(Array based)
void insert(int d) {
if(top==MAX-1) {
printf(“\n Sorry the list is full”);
return; Initial configuration of the List (Array-based)
0 1 2 3 4 5 6 7 .... ....
} MAX-1

++top; top = -1

s[top].data = d; After insertion of 5 elements in the List (Array-based)


} 0 1
MAX-1
2 3 4 5 6 7 .... ....

top = 4 74
Algorithm for traversing / displaying List ADT(Array
based)
void display() {
int i;
if(top == -1) {
printf(“\n Sorry the list is empty”);
return;
}
print(“\n The contents of the list are:”);
for(i = 0; i< =top; i++)
printf(“%d - -> ”, s[i].data);
} 75
Algorithm for deleting elements in a
List ADT(Array based)
void deletedata(int d){
int i;
if(top == -1) {
printf("\n Sorry the list is empty");
return ;
}
for(i=0;i<=top;i++)
if(s[i].data==d){
while(i<top){
s[i]=s[i+1];
++i;
}
}
--top;
} 76
Homework - 05/02/2024
Use the program in the link to include the following 3 algorithms (use separate functions for each
algorithm). Send the completed homework in a single file with all the following 3 algorithms
included.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjQ4MTg2NjUzNzkx/details
1. Write an algorithm to insert a node at the beginning of the array-based List ADT
2. Write an algorithm to find the minimum element node in the array-based List ADT
i) print min value in function itself
ii) return the min value alone / position of the min value in the list
iii) return the whole structure
3. Write an algorithm to find the maximum element node in the array-based List ADT
i) print max value in function itself
ii) return the max value alone / position of the max value in the list
iii) return the whole structure 77
Algorithm to insert a node at the beginning of the array-
based List ADT (Homework - 05/02/2024)
void insertbegin(int d) {
int i,j;
if(top==MAX-1) {
printf("\n Sorry the list is full");
return;
}
++top;
i=top-1;
for(j=i;j>=0;j--)
s[j+1]=s[j];
s[0].data=d;
} Code Courtesy
Lalitha P, Afra Rafeeqa H
II ECE C 78
Algorithm for finding the minimum elements in a List ADT(Array
based)
int minimum(){
int i,min;
if(top == -1) {
printf("\n Sorry the list is empty");
return;
}
min=s[0].data;
for(i=1;i<=top;i++)
if(s[i].data>min)
min=s[i].data;
return min; Code Courtesy
Lalitha P, Afra Rafeeqa H
} II ECE C 79
Algorithm for finding the maximum elements in a List ADT(Array
based)
int maximum(){
int i,max;
if(top == -1) {
printf("\n Sorry the list is empty");
return;
}
max=s[0].data;
for(i=1;i<=top;i++)
if(s[i].data>max)
max=s[i].data;
return max; Code Courtesy
Lalitha P, Afra Rafeeqa H
} II ECE C 80
Algorithm to modify / change value in a
List ADT(Array based)
void modify(int oldval,int newval){
int i;
if(top==-1){
printf("\nSorry List is Empty");
return;
}
for(i=0;i<=top;i++)
if(s[i].data==oldval){
s[i].data=newval;
return;
}
printf("\n Sorry the old value u look for is not found");
}
81
Algorithm for searching elements in a List ADT(Array based)

int search(int d){


int i;
if(top == -1) {
printf("\n Sorry the list is empty");
return -1;
}
for(i=0;i<=top;i++)
if(s[i].data==d)
return i;
return -1;
} 82
#
List Implementation with multiple data
Example
Code Name Price Quantity Category
struct store {
int code; 0 1001 Paper 10.00 250 Stationary

char name[10]; 1002 Pen 25.00 230 Stationary


.
float price; 1003 Eraser 5.00 85 Stationary

int quantity; .
char category[10];
} s[MAX]; .
.

MAX-1
5012 fivestar 10.00 150 Snacks
83
Homework - 06/02/2024
Use the program in the link to include the following 2 algorithms (use
separate functions for each algorithm). Send the completed homework in
a single file with all the following 2 algorithms included.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjQ4MTg2N
jUzNzkx/details
1. Write an algorithm for finding the sum and average of integer
elements in an array-based list ADT.
2. Write an algorithm to insert data at a particular mentioned position in
an array-based list ADT.

84
Algorithm for insertion at a particular position of a List ADT(Array
based)
void insertatposition(int pos,int d) {
int i,j;
if(top==MAX-1) {
printf("\n Sorry the list is full");
return;
}
++top;
i=top-1;
for(j=i;j>=pos;j--)
s[j+1]=s[j];
s[pos].data=d;
}
85
Lab Exercise - 1 ( First Program)
1. Write a C Program to Implement an Array based Linked List with
options for Insertion of a Node, Retrieve a Node, Delete a Node, Find
the position of an Element in a Node, Display the List, and Delete the
List. Each node should contain more than one element for carrying
out the mentioned operations.

Each batch to take unique problem statements for doing this exercise (with
minimum of four to five data in a node)
Example:
1) List of Students
2) List of Grocery items in a store
3) List of Player records
Etc., etc.,
Linked List-based
Implementation of List ADT

87
Linked list implementation (Pointer
based implementation)
▷ To avoid the linear (high) cost of insertion and deletion in the array
based implementation.
▷ Here list elements are not stored in contiguous memory location.
▷ Linked list have sequence of data / structures / nodes linked
through pointers.
▷ Uses self-referential structure. They have collection of elements in
a structure (nodes).
▷ Each node in linked list has minimum of two fields
○ Data Field (Elements)
○ Address Field (Link for the other node)
Linked list implementation (Pointer
struct node{
based implementation)
int data; //store the data
struct node *next; //hold the address of next node
Self-referential pointer
} (i.e., pointer for the same node/structure itself)
▷ Member of the structure struct node *next; points to the same
node / structure itself. So, the name linked list.
▷ Head pointer - Always points to the first node in the linked list
▷ NULL pointer - It always indicates the end of the linked list
▷ Last cell in the linked list (of the last node) have the NULL
address / pointer
Homework -08/02/2024
How many data metrics / data fields are used in the
implementation if data structures used in the development of the
following platforms
1) Facebook - 92
2) Twitter - 40
3) LinkedIn - 50
4) WhatsApp - 40
5) Instagram - 81
6) Google Maps - 60
7) Quora - 40 Data Shared by
Afra Rafeeqa H
II ECE C 90
Types of Linked List

1)Single Linked List


2)Double Linked List
3)Circular Linked List
i) Singly Circular Linked List
ii) Doubly Circular Linked List
91
Singly Linked list

Head Pointer NULL


Pointer
Doubly Linked list

X X

NULL NULL
Pointer Pointer
Head Pointer Tail Pointer
Singly Circular Linked list

Head Pointer
Doubly Circular Linked list

Head Pointer Tail Pointer


Advantages of Linked List

▷ Cost of insertion and deletion of elements in a linked list is


constant and its drastically low compared to array based
implementation.
▷ It reduces the processing / execution time of certain vital
algorithms.
▷ Its dynamic nature. We can allot memory on the go and
access the data accordingly.

96
Disadvantages of Linked List

▷ No element can be accessed in a random fashion. All


the elements can be only accessed in a sequential
order.
▷ We need extra storage for holding the address of the
next node / element in the list.
▷ Reverse traversing is challenging, unless you don't
have extra pointers.
97
Applications of Linked List
Linked lists are used in many real-world applications.
Being a basic dynamic data structures, linked lists are always
used for the implementation of other popular data structures like
1) Stack
2) Queue
3) Trees
4) Graphs
5) Hash Tables
6) etc.,
98
Single Linked List
Implementation of List ADT

99
Implementation
In a single of Singly
linked list, each structure Linked
(node) containslist
elements
(data) and pointer (address) to the next structure (node).

Head Pointer NULL


These set of nodes form a linear data structure with each nodes
Pointer
linked to its successor.
Steps for Implementation of Singly
Linked list

1. Create Node (using structure- self referencial)


2. Initialize the pointers for the node (head pointer,
traversal pointer, temp pointer)
3. Write algorithms for
a. Insertion of elements (data)
b. Link the nodes
c. Repeat the same process for other algorithms also.
Creation of nodes in a Singly Linked list

//A node with single data //A node with multiple data
struct node{ struct node{
int data; //store the data int sno; //store the data
struct node *next; //hold the address of next node
char name[10]; //store the data
}
int rollno; //store the data
float cgpa; //store the data
struct node *next; //hold the address of next node
}
Single Linked List based
implementation of List ADT
Problem Statement / Aim / Objective
To implement the Single Linked list for the List ADT on a set of numbers (marks of students / set of
integers / scores by a individual players in certain number of innings). Write appropriate (following set of)
algorithms for handling the available data (set of numbers ) and to structure them (Data structure)
1) Insert
a) Insert at a particular location
b) Insert before / after a particular value
c) Insert at beginning
d) Insert at end etc.,
2) Display
3) Modify Write a C program to implement the given problem statement with
4) Search separate functions for each and every algorithm.
5) Delete
a) Based on value
b) Based on location
c) Delete at beginning of list
d) Delete at end etc.,
6) Clear
7) etc.,
C Program template for implementation
#include<stdio.h>
//list down all the function prototypes to be used in the implementation
void insert(int);
void display();
void modify(int, int); //pass old data and new data to be modified
int search(int); //pass value to be searched and get the location
void delete(int); //pass location or value to be deleted
etc.,etc.,
struct node{
int data; //store the data
struct node *next; //hold the address of next node
}*head = NULL, *p=NULL, *temp=NULL
Node creation for single linked list
ADT
struct node{
int data; //store the data
struct node *next; //hold the address of next node
}*head = NULL, *p=NULL, *temp=NULL;

*head - Head pointer, it always points to the first node in the linked list.
*p - Pointer to traverse from the first node to the last node ( or to traverse in between the
nodes in a linked list)
*temp - Meant for creating new nodes, or for doing temporary operations in the linked
list.
Initially all the pointers are made NULL (means that list is empty or the list is not
created)
Algorithm for inserting into List ADT(Single Linked List)
void insert(int d){
temp = (struct node*)malloc(sizeof(struct node));
temp->data=d;
temp->next=NULL;
During insertion of 1st node
if(head==NULL){ //if the list is empty
head = temp; During insertion of 2nd node

return; For insertion from 3rd node


} onwards

p=head; //initialize the first node to ‘p’


while(p->next!=NULL) //traverse till the end of the list
p=p->next; //gets traversed to the next node
in the list
p->next=temp;
printf("\nNode inserted successfully"); 106
Algorithm for displaying List ADT(Linked List based)
void display(){
if(head==NULL){
printf("\nSorry the list is empty");
return;
}
p=head;
while(p!=NULL){ //traverse till the last node in the list
printf("%d-->", p->data); //gets traversed to the next node in
the list
p=p->next;
}
107
Homework - 12/02/2024
Use the program in the link to include the following 2 algorithms
(use separate functions for each algorithm) in the Single-linked
List. Send the completed homework in a single file with the
following 2 algorithms included.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjQ4
MzcyMjc0Njc3/details
1) Write an algorithm to count the number of nodes in a single
linked list.
2) Write an algorithm to delete the last node in a single linked list

108
Write an algorithm to count the number of nodes in a single linked
int nodecount(){ list. (Homework - 12/02/2024)
int count=0;
if(head==NULL){
printf("\nSorry List is empty");
return;
}
p=head;
while(p!=NULL){
count++;
p=p->next;
}
return count; Code Courtesy
Gauresh Kumar G, Lalitha
} P 109
II ECE C
Algorithm for deletion based on value in a Single
Linked List ADT(Linked List based)
void deletevalue(int d){
if(head==NULL){
printf("\nSorry the list is empty");
return; After the last iteration of while loop or
after finding the data to be deleted
} Node to be
deleted

p=head; head temp


d
p p->next
X

while(p->data!=d){
After deleting the node ‘p’
temp=p;
p=p->next; temp
d
p p->next
X
head
}
temp->next=p->next;
free(p);
printf("\nData removed successfully");
110
}
Algorithm for deletion based on position in a
void deletepos(int pos){ List ADT(Linked List based)
int c=0;
if(head==NULL){
printf("\nSorry the list is empty");
return; After the last iteration of while loop or
} after finding the position of the node to be deleted
Position of the Node to be

p=head; deleted
d X
temp p p->next
while(p->next!=NULL && c!=pos){ head

c++; After deleting the node ‘p’


temp=p;
p=p->next; temp
d
p p->next
X
head
}
temp->next=p->next;
free(p);
printf("\nData removed successfully");
}
111
Algorithm for delete the first node in a List ADT(Linked List based)
Before deleting the head node
void deletefirst(){ Node to be
deleted

if(head==NULL){ p=head p->next


X

printf("\nSorry the list is empty");


return; After deleting the head node
} X
head

p=head;
head=p->next; //(or) head=head->next;
free(p);
printf("\nFirst node is deleted");
112
}
Algorithm for deleting the last node in a List
void deletelast(){
ADT(Linked List based)
if(head==NULL){
printf("\nSorry the list is empty");
return;
}
Before deleting the last node
p=head; Node to be
deleted

while(p->next!=NULL){ head temp p


X

temp=p;
p=p->next;
After deleting the last node
}
temp->next=NULL; head
X
temp
X

free(p);
113
}
Algorithm for insert the first node in a List
ADT(Linked List based)
void insertfirst(int d){
temp = (struct node*)malloc(sizeof(struct node));
temp->data=d; Before inserting @ First location as head node
temp->next=NULL;
if(head==NULL){
X
head

head=temp; d X New node

return; temp

After inserting @ the First location as head node


} New node inserted
as head

temp->next=head; d
head = temp
X

head=temp;
printf("\nNode inserted @ First place"); 114
Algorithm for modify a value in a List ADT(Linked List based)
void modify(int oldd, int newd) {
if (head == NULL) {
printf("\nSorry the list is empty");
return;
}
p = head;
while (p != NULL) {
if (p->data == oldd) {
p->data = newd;
printf("\nValue modified successfully");
return;
}
p = p->next;
}
printf("\nValue %d not found in the list", oldd);
} 115
Homework - 14/02/2024
Use the program in the link to include the following 2 algorithms
(use separate functions for each algorithm) in the Single-linked
List. Send the completed homework in a single file with the
following 2 algorithms included.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjQ4
MzcyMjc0Njc3/details
1) Write an Algorithm for Single Linked List to swap the elements
in the first and second nodes.
2) Write an Algorithm for Single Linked List to find the sum and
average of integer elements in the list.

116
Algorithm for Single Linked List to swap the elements in the
first and second nodes. (Homework - 14/02/2024)
struct node{
int data; //store the data
struct node *next; //hold the address of next node
}*head = NULL, *p=NULL, *temp=NULL,*first=NULL, *second=NULL;

void swap(){
if(head==NULL || head->next==NULL){
printf("\n swapping is not possible");
return;
}
first=head;
second=head->next;
first->next=second->next;
second->next=first;
head=second; Code Courtesy
Lalitha P
} II ECE C 117
Homework - 15/02/2024
Use the program in the link to include the following 2 algorithms
(use separate functions for each algorithm) in the Single-linked
List. Send the completed homework in a single file with the
following 2 algorithms included.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjQ4
MzcyMjc0Njc3/details
1) Write an Algorithm for Single Linked List to return node with
minimum element (return the whole node) to main
2) Write an Algorithm for Single Linked List to return node with
maximum element (return the whole node) to main

118
Algorithm for Single Linked List to return node with minimum element
(return the whole node) to main (Homework - 15/02/2024)
struct node* minimum(){
if(head==NULL){
printf("\nSorry the list is empty");
return NULL; Call from main() function
.
} .
temp = head; .
struct node* min=minimum();
p = head->next;
printf("\nMinimum element is %d",min->data);
while(p != NULL){ struct node* max=maximum();
if(p->data < temp->data) printf("\nMaximum element is %d",max->data);
return 0;
temp = p;
}
p = p->next;
}
return temp;
} Code Courtesy
Lalitha P
II ECE C 119
Algorithm for Single Linked List to return node with maximum element
(return the whole node) to main (Homework - 15/02/2024)
struct node* maximum(){
if(head==NULL){
printf("\nSorry the list is empty");
return NULL; Call from main() function
.
} .
temp = head; .
struct node* min=minimum();
p = head->next;
printf("\nMinimum element is %d",min->data);
while(p != NULL){ struct node* max=maximum();
if(p->data > temp->data) printf("\nMaximum element is %d",max->data);
return 0;
temp = p;
}
p = p->next;
}
return temp;
} Code Courtesy
Lalitha P
II ECE C 120
Double Linked List
Implementation of List ADT

121
Implementation of Doubly Linked
list
In a double linked list, each structure (node) contains elements
(data) and pointer (address) to the next structure (node) and
pointer to previous structure (node).
X X

NULL NULL
Pointer Pointer
Head Pointer Tail Pointer

These set of nodes form a linear data structure with each nodes
linked to its successor and predecessor.
Double Linked List based implementation
of List ADT
Problem Statement / Aim / Objective
To implement the Double Linked list for the List ADT on a set of numbers (marks of
students / set of integers / scores by a individual players in certain number of innings).
Write appropriate (following set of) algorithms for handling the available data (set of
numbers ) and to structure them (Data structure)
1) Insert
a) Insert at a particular location
b) Insert before / after a particular value
c) Insert at beginning
d) Insert at end etc.,
2) Display
a) Forward Write a C program to implement the given problem statement with separate
b) Reverse functions for each and every algorithm.
3) Modify
4) Search
5) Delete
a) Based on value
b) Based on location
c) Delete at beginning of list
d) Delete at end etc.,
6) Clear
7) etc.,
Creation of nodes in a Double Linked list

//A node with single data //A node with multiple data
struct node{ struct node{
int data; //store the data int sno; //store the data
struct node *next; //hold the address of next node
char name[10];
struct node *prev;//hold the address of previous node
int rollno;
} float cgpa;
struct node *next; //hold the address of next node

struct node *prev; //hold the address of previous node

}
Node creation for Doubly linked list
struct node{ ADT
int data; //store the data
struct node *next; //hold the address of next node
struct node *prev; //hold the address of previous node
}*head = NULL, *tail=NULL, *p=NULL, *temp=NULL;
*head - Head pointer, it always points to the first node in the linked list.
*tail - Tail pointer, it always points to the last node in the linked list.
*p - Pointer to traverse from the first node to the last node / last node to first node ( or to traverse in
between the nodes in a linked list)
*temp - Meant for creating new nodes, or for doing temporary operations in the linked list.
Initially all the pointers are made NULL (means that list is empty or the list is not created)
Algorithm for inserting into Doubly Linked List ADT
void insert(int d){
temp = (struct node*)malloc(sizeof(struct node));
temp->data=d;
temp->next=NULL;
temp->prev=NULL;
if(head==NULL){ //if the list is empty During insertion of 1st node
head = temp;
tail=temp; During insertion of 2nd node
return; For insertion from 3rd node
} onwards
p=head;
while(p->next!=NULL) //traverse till the end of the list
p=p->next; //gets traversed to the next node in the
list
p->next=temp;
temp->prev=p;
tail=temp; 126
printf("\nNode inserted successfully");
Algorithm for displaying forward traversal in a Doubly Linked List
ADT

void displayforward(){
if(head==NULL){
printf("\nSorry the list is empty");
return;
}
p=head;
while(p!=NULL){ //traverse till the last node in the list
printf("%d-->",p->data);
p=p->next;
}
}
127
Algorithm for displaying reverse traversal in a Doubly Linked List
ADT

void displayreverse(){
if(tail==NULL){
printf("\nSorry the list is empty");
return;
}
p=tail;
while(p!=NULL){ //traverse till the first node in the list
printf("%d-->",p->data);
p=p->prev;
}
}
128
Algorithm for deleting a data in a Doubly
Linked List ADT based on value
void deletevalue(int d){
if(head==NULL){
printf("\nSorry the list is empty");
return;
}
p=head;
while(p->data!=d){
temp=p;
p=p->next;
}
temp->next=p->next;
p->next->prev=temp;
free(p);
printf("\nData removed successfully"); 129
}
Homework - 16/02/2024
Use the program in the link to include the following algorithms (use separate functions
for each algorithm) in the Double-linked List. Send the completed homework in a
single file with the following algorithms included.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjQ4NzQ5MjEyMT
Y4/details

1) Write an Algorithm for deletion of a node based on position in a Double Linked List
ADT
2) Write an Algorithm for deleting the first node in a Double Linked List ADT
3) Write an Algorithm for deleting the last node in a Double Linked List ADT
4) Write an Algorithm for inserting the first node in a Double Linked List ADT
5) Write an Algorithm for modifying a value in a Double Linked List ADT
130
Algorithm for deletion of a node based on position in a Double Linked List
void deletepos(int pos){ ADT (Homework - 16/02/2024)
int c=0;
if(head==NULL){
printf("\nSorry the list is empty");
return;
}
p=head;
while(p->next!=NULL && c!=pos-1){
c++;
temp=p;
p=p->next;
}
temp->next=p->next;
p->prev=temp;
free(p);
Code Courtesy
printf("\nData removed successfully"); Bala Saravanan M, Lalitha P
II ECE C 131
}
Algorithm for deletion of the first node in a Double Linked List ADT
(Homework - 16/02/2024)
void deletefirst(){
if(head==NULL){
printf("\nSorry the list is empty");
return;
}
p=head;
head=p->next;
head->prev=NULL;
free(p);
printf("\nFirst node is deleted"); Code Courtesy
Bala Saravanan M, Lalitha P
} II ECE C 132
Algorithm for deleting the last node in a Double Linked List ADT
(Homework - 16/02/2024)
void deletelast(){
if(tail==NULL){
printf("\nSorry the list is empty");
return;
}
p=tail;
tail = p->prev;
tail ->next=NULL;
free(p);
}
Code Courtesy
Bala Saravanan M, Lalitha P
II ECE C 133
Algorithm for inserting the first node in a Double Linked List ADT
(Homework - 16/02/2024)
void insertfirst(int d){
temp = (struct node*)malloc(sizeof(struct node));
temp->data=d;
temp->prev=NULL;
if(head==NULL){
head=tail=temp;
temp->next=NULL;
return;
}
temp->next=head;
head->prev=temp;
head=temp; Code Courtesy
} Bala Saravanan M, Lalitha P
II ECE C 134
Algorithm for modifying a value in a Double Linked List ADT
void modify(int oldd, int newd) { (Homework - 16/02/2024)
if (head == NULL) {
printf("\nSorry the list is empty");
return;
}
p = head;
while (p != NULL) {
if (p->data == oldd) {
p->data = newd;
printf("\nValue modified successfully");
return;
}
p = p->next;
}
printf("\nValue %d not found in the list", oldd); Code Courtesy
} Bala Saravanan M, Lalitha P
II ECE C 135
Unit - I
Algorithm Analysis and Linear Data Structures - List
● Algorithm
● Mathematical preliminaries on analysis.
● Run-time and space complexity analysis of algorithm
● Data Structures
● Abstract Data Type (ADT)
● List ADT (Data Structure)
○ Array based
○ Linked list based
■ Single Linked list
■ Doubly linked list
■ Circular linked list
136
Algorithms
&
Mathematical Preliminaries

137
Algorithms
▷ Outlines the essence of computation procedures
through step by step instructions.
▷ In the context of data structure, algorithms are meant
to give proper structure to the data.
▷ Transforms input to output through the computation
procedures.
▷ An important step is to determine, how many
resources (i.e. in terms of memory, time and
space) are required by the algorithm.
▷ A best algorithm should consume very minimum
resources.
Properties of Algorithms

1. Finitiness
2. Absence of Ambiguity
3. Definition of sequence
4. Feasibility
5. Input
6. Output
Mathematical preliminaries on
analysis.
▷ The analysis required to estimate the resources used by an
algorithm from the theoretical perspective ( in terms of formule
and expressions).
▷ A formal framework of notations (mathematical) will be used for
carrying out the algorithm analysis.
▷ They address both qualitative and quantitative aspects of the
algorithms.
▷ Further, they are also helpful to compute the economical aspects
of computational performance of the algorithms.
What is to be analysed?
1) Running (Execution) time of the algorithm
Even Though, it differs based on computer configuration (Processor,
RAM, OS etc.,) we need to consider only size or number of inputs
(N) for algorithm analysis.
2) Memory (Space) occupied by the data in the algorithm
Even Though, it differs based on computer configuration (Processor,
RAM, OS etc.,) we need to consider the variables and the type /
number of looping statements used in the algorithm for analysis.
Popular Notations for Algorithm
Analysis (Asymptotic notations)
1. Big Oh(O) - Upper bound (worst case )
2. Big Omega (Ω) - Lower bound (best case )
3. Big Theta (𝚯) - Two-way bound (average case )
4. Small / Little Oh(o) - Only upper bound (worst case analysis )
5. Small Omega (⍵) - Rough estimate of the order of the growth
6. Small Theta (𝝷) - Tight bound on the growth rate of runtime of an
algorithm.
Among the given notation Big Oh(O) plays a crucial role in determining
the accuracy of the algorithm analysis.
A best algorithm must not run beyond the limit specified by Big Oh(O)
Big Oh (O) Notation

▷ It defines the upper bound of the algorithm and the defined function
will not grow faster than the specified limit.
▷ Used to access the worst case run time of the algorithm and highly
concerned with the larger number of inputs (n)

f(n) = O(g(n))
▷ Where, the function f(n) will not grow faster than the function g(n)
▷ This stays true, if f(n) <c g(n), for all n>no and c is +ve constant.
Big Oh(O) - Upper bound (worst case )
Running Time / Space

Number of inputs (n)

144
Big Omega(Ω) Notation

▷ It defines the lower bound of the algorithm and the defined function
will not go below than the specified limit.
▷ Used to access the best case run time of the algorithm and highly
concerned with the larger number of inputs (n)

f(n) = Ω(g(n))
▷ Where, the function f(n) will not go below than the function g(n)
▷ This stays true, if f(n) > c g(n), for all n>no and c is +ve constant.
Big Omega (Ω) - Lower bound (best case)

Running Time / Space

Number of inputs (n)


146
Big Theta(𝚯) Notation

▷ It defines the average bound of the algorithm and the defined function
will not exceed or go below than the specified limit.
▷ Used to access the average case run time of the algorithm and
highly concerned with the larger number of inputs (n)

f(n) = 𝚯(g(n))
▷ Where, the function f(n) will not exceed or go below than the
function g(n)
▷ This stays true, if c2 g(n) > f(n) > c1 g(n), for all n>no and c1 and c2
are +ve constants.
Big Theta (𝚯) - Two-way bound (average case)

Running Time / Space

Number of inputs (n)

148
Homework - 19/02/2024

1) Differentiate Big Oh (O) and Little Oh (o) & give


their mathematical representation
2) Differentiate Big Omega (Ω) and Little Omega (⍵) &
give their mathematical representation
3) Differentiate Big Theta (𝚯) and Little Theta (𝝷) &
give their mathematical representation

149
Time / Space / Resource complexity for
Big-Oh (O) notation
Big Oh Representation Name

O(1) Constant

O(log N) Logarithmic

O(N) Linear

O(N2) Quadratic

O(N3) Cubic

O(2N) Exponential

O(N!) Factorial

etc.,
Number of
Run time Complexity of Algorithms
Run-time and space
complexity analysis of
algorithm

153
Run-time and space complexity analysis of
algorithm
Find the worst case running time and space of the following algorithm and
analyse the algorithm with Big Oh(O) implementation.
int sum(int N){
int i,s;
i=0; =>(1 assign) => 1 unit
s=0; =>(1 assign) => 1 unit
for(i=1;i<=N;i++) =>(1 assign, N+1 testing, N increment) => 2N+2 units
s+=i; =>(1 add, 1 assign- happens N times) => 2N
units
return s;
}
Ignoring the calling costs and returning functions, we have total of 4N+4
=> So, the function is O(N). Therefore, worst case run time of the algorithm is
O(N).
Space complexity: For storing/processing N elements, N memory locations
needed. Therefore, worst case space complexity of the algorithm is O(N).
Worst case run time of looping
statements
What is the worst case run time of this looping statement
for(i=0;i<N;i++)
for(j=0;j<N;j++)
a++;
O(N2) - Since we have two nested loops running NxN times
What is the worst case run time of this looping statement
for(i=0;i<N;i++)
for(j=0;j<N;j++)
for(k=0;k<N;k++)
a++;
O(N3) - Since we have three nested loops running NxNxN times
Worst Case Run-time complexity of List ADT
Insertion Algorithms
ADT Type Insert @ Insert @ particular Insert @ End
beginning Position

Array based O(N) O(1) - finding the O(1)


position
O(N) - Insertion
Single Linked O(1) O(N) - finding the O(N)
List position
O(1) - Insertion
Double Linked O(1) O(N) - finding the O(1)
List position
O(1) - Insertion
156
Worst Case Run-time complexity of List ADT
Deletion Algorithms
ADT Type Delete @ Delete @ particular Delete @ End
beginning Position

Array based O(N) O(1) - finding the O(1)


position
O(N) - deletion
Single Linked O(1) O(N) - finding the O(N)
List position
O(1) - deletion
Double Linked O(1) O(N) - finding the O(1)
List position
O(1) - deletion
157
Worst Case Run-time complexity of List ADT
Traversal / Search / Modify Algorithms
ADT Type Traversal Search Modify

Array based Forward - O(N) Position - O(1) Position - O(1)


Reverse - O(N) Data - O(N) Data - O(N)
Single Linked O(N) Position - O(N) Position - O(N)
List Data - O(N) Data - O(N)

Double Linked Forward - O(N) Position - O(N) Position - O(N)


List Reverse - O(N) Data - O(N) Data - O(N)

158
Worst Case Space complexity of List ADT
ADT Type Space Complexity

Array based O(N)

Single Linked List O(N)

Double Linked List O(N)

159
Homework - 21/02/2024

1) Analyze the worst-case run-time and space


complexity of the bubble sorting algorithm, and give
its Big Oh representation.
2) Analyze the worst-case run-time and space
complexity of the algorithm to find the maximum
element in an array
3) Analyze the worst-case run-time and space
complexity of swapping algorithm
160
Homework - 22/02/2024

1) Find the best case and average case of all the


algorithms in the array-based list, single-linked list
and doubly-linked list
2) Analyze the best-case, worst-case, and average case
of the Fibonacci series algorithm.
3) Analyze the best-case, worst-case, and average case
of the sum of the digits algorithm.

161
Steps to follow for writing the
Algorithms in Test
1) Description on the problem statement and data structures.
2) Pictorial representation of data structure before execution of
the algorithm
3) Write the algorithm (include comments where necessary)
4) Pictorial representation of data structure after execution of
the algorithm
5) Worst / Best/ Average case run time / space complexity
analysis with Big Oh representation (with description)

162
Polynomial Manipulation
using Lists

163
164
165

End of Unit - I

166
UNIT - II

Linear Data Structures - Stack and


Queue

167
UNIT II
LINEAR DATA STRUCTURES-STACK AND QUEUE

▷ Stack ADT
○ Array–based
○ Linked list–based
▷ Applications of Stack
○ Balancing Symbols
○ Postfix Expressions
○ Infix to Postfix Conversion
▷ Queue ADT
○ Array–based
○ Linked list–based
▷ Types of Queue
▷ Applications of queues
Stack ADT

169
Stack ADT
▷ It's a derived concept of List,
▷ Restriction that insertion and deletion can be performed at only end.
(Top of the stack).
▷ Stacks are also called as Last In First Out (LIFO)
▷ Top pointer (index) always points to the top most element of a stack
Operations on Stack
1) PUSH - Equivalent to insert operation
2) POP - Equivalent to delete operation (recently inserted element)
▷ Performing PUSH operation when memory is full - is an error.
▷ POP operation in an empty stack - is an error.
171
Implementation of Stack ADT

1) Array based Implementation


▷ Size of the stack need to be defined (i.e. its fixed)
▷ Only finite amount of elements could be stored
▷ top==-1 (means stack is empty; i.e. stack
underflow)
▷ top == MAX-1 (means stack is full; i.e. stack
overflow)
Array based implementation of Stack ADT
Problem Statement / Aim / Objective
To implement the array based Stack ADT for a set of numbers (marks of students / set of integers /
scores by a individual players in certain number of innings). Write appropriate (following set of)
algorithms for handling the available data (set of numbers ) and to structure them (Data structure)

1) PUSH
2) Display
3) POP
Write a C program to implement the given problem statement with separate
4) ModifyTOP functions for each algorithm.

5) Peek
6) isEmpty
7) isFull
8) Clear
9) etc.,
174
Algorithm for PUSH Operation in Stack (Array
based)
void PUSH(int d) {
if(top==MAX-1) {
printf(“\n Sorry the Stack is full: Stack Overflow”);
return;
}
++top;
s[top].data = d;
}
175
Algorithm for displaying the
contents of array based stack ADT
void display(){
if(top==-1){
printf(“\nSorry stack is empty:Stack underflow”);
return;
}
for(i=top;i>=0;i- -)
printf(“\n%d”,s[i].data);
}
Algorithm for deletion (POP) from
an array based stack ADT
int POP(){
int x;
if(top==-1){
printf(“\nSorry stack is empty:Stack underflow”);
return;
}
x=s[top].data;
--top;
return x;
}
Implementation of Stack ADT
2) Linked List based Implementation
▷ Size of the stack need not be defined ( dynamic)
▷ We can hold infinite amount of elements in the
stack (subjected to size of RAM)
▷ top==NULL (means stack is empty; i.e. stack
underflow)
▷ Stack will not get filled to its maximum (subjected
to size of RAM)
Linked List based implementation of Stack ADT
Problem Statement / Aim / Objective
To implement the linked list based Stack ADT for a set of numbers (marks of students / set of
integers / scores by a individual players in certain number of innings). Write appropriate (following
set of) algorithms for handling the available data (set of numbers ) and to structure them (Data
structure)

1) PUSH
2) Display
Write a C program to implement the given problem statement with separate
3) POP functions for each algorithm.

4) ModifyTOP
5) Peek
6) isEmpty
7) Clear
8) etc.,
179
Linked List based implementation
of Stack ADT
Node Creation
//Node creation
struct node {
int data;
struct node *next;
} *top=NULL, *p=NULL, *temp=NULL;
Algorithm for insertion (PUSH) in
Linked List based stack ADT
void PUSH(int d){
temp=(struct node*) malloc(sizeof(struct node));
temp->data = d;
if(top==NULL){
top=temp;
top->next=NULL;
return;
}
temp->next = top;
top =temp;
}
Algorithm for displaying the contents of Linked List based Stack
void display(){
ADT
if(top==NULL){
printf("\nSorry the Stack is empty: Stack Underflow");
return;
}
p=top;
while(p!=NULL){ //traverse till the last node in the stack
printf("\n%d",p->data);
p=p->link;
}
} 182
Algorithm for deletion (POP) from an
Linked-list based stack ADT
int POP(){
int x;
if(top==NULL){
printf("\nSorry stack is empty:Stack underflow");
return;
}
x=top->data;
top=top->next;
return x;
}
Algorithm for Peek from an Linked-
list based stack ADT
int Peek(){
int x;
if(top==NULL){
printf("\nSorry stack is empty:Stack underflow");
return;
}
x=top->data;
return x;
}
Algorithm for deletion (POP) from an Linked-list
based stack ADT (Return whole node)
struct node* POPNode(){
if(top==NULL){
printf("\nSorry stack is empty:Stack underflow");
return;
}
p=top;
top=top->next;
return p;
} 185
Algorithm for Peek from an Linked-list based stack
ADT (Return whole node)
struct node* PeekNode(){
if(top==NULL){
printf("\nSorry stack is empty:Stack underflow");
return;
}
p=top;
return p;
} 186
Algorithm for isEmpty in a Linked-list based stack
ADT
int isEmpty(){
return (top == NULL); // Returns 1 if stack is empty, else returns 0
}

187
Algorithm for ModifyTOP in an Linked-list based
stack ADT
void ModifyTOP(int newData){
if(isEmpty()){
printf("\nSorry stack is empty: Cannot modify TOP");
return;
}
top->data = newData;
}
188
Homework - 26/02/2024
Use the program in the link to implement the following
algorithms in an Array based Stack ADT implementation.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/
NjU4ODExNTIyODg2/details
1. Write an algorithm to POP the whole node (structure) in an
array-based Stack implementation.
2. Write an Algorithm to reverse the contents of a string, where
each character was PUSHed into the stack one after another.
Use the POP operation in array-based stack implementation
to reverse the string.
189
Worst Case Run-time complexity of Stack ADT
Algorithms
ADT Type PUSH POP Traversal Peek ModifyTop isEmpty

Array O(1) O(1) O(N) O(1) O(1) O(1)


based
Single O(1) O(1) O(N) O(1) O(1) O(1)
Linked
List

190
Applications of Stack ADT

191
Applications of Stack

1. String Reversal
2. String Concatenate
3. Backtracking
4. Balancing Parenthesis
5. Infix to Postfix Expression Conversion
6. Postfix Expression Evaluation
7. etc.,
192
Homework - 28/02/2024
Use the program in the link to implement the following
algorithms in an Linked List based Stack ADT implementation.
https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjU
4ODEyMDgyMjY1/details
1. Write an algorithm to create two stacks with top1 and top2
pointers and merge them into a single stack.

193
Ex 1: Move the contents from One
stack to another stack

Write an algorithm to move the data / nodes from one stack to another stack using
linked list based implementation of stack ADT.

Assume: you have already implemented separate algorithms for PUSH and POP for
both the stacks.
Option 2:
Option 1:
Void PUSH1(int d); //Algorithm to push in stack1 In a single PUSH and POP

Void PUSH2(int d); //Algorithm to push in stack2 functions, pass the stack reference

Int POP1(); // Algorithm for POP from stack1 as an additional argument

Int POP2(); .//Algorithm for POP from stack2 (top1/top2) 194


Ex 2: Reverse a String using Stack
▷ Create a char[] to store a string.
▷ Create a Stack.
▷ Push all characters, one by one.
▷ Then Pop all characters, one by one and put into the char[].
▷ Finally, convert to the String.

195
Ex 3: Move and merge the contents of two
stacks to the third stack
Write an algorithm to merge the data / nodes from two different stacks, one after another stack
using linked list based implementation of stack ADT into the third stack.

Assume: you have already implemented separate algorithms for PUSH and POP for the three
stacks.
Option 1: Option 2:
Void PUSH1(int d); //Algorithm to push in stack1
In a single PUSH and POP
Void PUSH2(int d); //Algorithm to push in stack2

Void PUSH3(int d); //Algorithm to push in stack3 functions, pass the stack reference

Int POP1(); // Algorithm for POP from stack1 as an additional argument

Int POP2(); .//Algorithm for POP from stack2 (top1/top2/top3)

Int POP3(); .//Algorithm for POP from stack3 196


Ex 4: Concatenate two strings using
stack

▷ Create char[] to store a string.


▷ Create two Stacks with two different strings.
▷ Push the characters of each string, one by one to each stack.
▷ Pop all characters from stack1, one by one and push to stack3
▷ Pop all characters from stack2, one by one and push to stack3
▷ Pop all characters from stack3, one by one and put into the char[].
▷ Finally, convert to the String.

197
Ex.5 Algorithm for Balancing Parenthesis
int balance(char *exp){ (using stack)
n=strlen(exp);
for i=0;i<=n;i++{
if (exp[i] equal to any of the open bracket)
PUSH(exp[i]);
else if (exp[i] equal to any of the close bracket){
if (stack is empty (or) exp[i] is not equal to its pair)
return 0; //or print not balanced
else
POP();
}
if(stack is not empty)
return 0; //or print not balanced
else
return 1; //or print balanced
} 198
Ex. 6 Infix to Postfix Conversion
(using stack)
Infix Expression
Ex: A + B
Postfix Expression
Ex: AB +
Prefix Expression
Ex: + AB
199
Ex. 6 Infix to Postfix Conversion
(using stack)
Infix Expression Postfix Expression
1) A + B + C 1) ABC++
2) A * (B+C) 2) ABC+*
3) (A/B) * C 3) AB/C*
4) [(5+8)-4]*3 4) 58+4-3*
5) 6*{[5+[(2*3)+8]]-3} 5) 6523*8++3-*

200
Ex. 7 Postfix Expression Evaluation
(using stack)
Let A = 5, B = 6 , C =3
Postfix Expression Evaluated Expression
1) ABC++ 1) 14
2) ABC+* 2) 45
3) AB/C* 3) 2.5
4) 58+4-3* 4) 27
5) 6523*8++3-* 5) 96

201
Homework - 06/03/2024
Check weather the following expressions are
i) Balanced
ii) If balanced convert them to postfix
iii) Evaluate the postfix expression.
1) 4+{[(7*3)+5]+(2-8)}
2) a-{b*[c/(d+e)]-f}/g; Let a =5, b=3, c=10, d= 2, e=1, f=4, g=2
3) 9+{4-[2*4]-7*(2-8)}
▷ Illustrate the implementation using Stack ADT using
appropriate visual illustrations.
▷ Write the Dequeue Algorithm for Array Based Queue
202
Queue ADT

203
Queue ADT
▷ It's a derived concept of List, with restriction that insertion can
be done only at the end and the deletion only at the beginning
Operations on Queue
1) ENQUEUE- Equivalent to insert operation
2) DEQUEUE- Equivalent to delete operation (First inserted
element)
▷ Queues are also called as First in First Out (FIFO)
▷ Performing ENQUEUE operation when memory is full -
is an error.
▷ DEQUEUE operation in an empty queue- is an error.
Implementation of Queue ADT

1) Array based Implementation


▷ Size of the queue need to be defined (i.e. its fixed)
▷ Only finite amount of elements could be stored
▷ front==-1 and/or rear ==-1 (means queue is empty;
i.e. queue underflow)
▷ Rear == MAX-1 (means queue is full; i.e. queue
overflow)
Array based implementation of Queue ADT
Problem Statement / Aim / Objective
To implement the array based Queue ADT for a set of numbers (marks of students / set of
integers / scores by a individual players in certain number of innings). Write appropriate (following
set of) algorithms for handling the available data (set of numbers ) and to structure them (Data
structure)

1) Enqueue
2) Display
Write a C program to implement the given problem statement with separate
3) Dequeue functions for each algorithm.

4) ModifyFront / ModifyRear
5) PeekFront / PeekRear
6) isEmpty
7) isFull
8) Clear
9) etc., 206
Algorithm for insertion (Enqueue) in array based
queue ADT
//Algorithm for ENQUEUE
void ENQUEUE(int d){
if(rear==MAX-1){
printf("\nSorry Queue is full;Overflow");
return;
}
if(front==-1)
++front;
++rear;
s[rear].data=d;
207
}
Algorithm for displaying the contents of array
based
//Algorithm for traversal / display
Queue ADT
void display(){
int i;
if(rear==-1){
printf("\nSorry Queue is empty;Underflow");
return;
}
printf("\nThe Queue contents are:");
for(i=front;i<=rear;i++)
printf("%d-->",s[i].data);
} 208
Algorithm for deletion (Dequeue) in array based
queue ADT
int dequeue(){
int x;
if(front==-1){
printf("\nSorry Queue is empty:Queue Underflow");
return;
}
x=s[front].data;
front++;
if(front==rear+1)
front=rear=-1;
return x;
} 209
Implementation of Queue ADT

2) Linked List based Implementation


▷ Size of the Queue need not be defined ( dynamic)
▷ We can hold infinite amount of elements in the
Queue (subjected to size of RAM)
▷ front==NULL or rear==NULL (means Queue is
empty; i.e. Queue underflow)
▷ Queue will not get filled to its maximum (subjected
to size of RAM)
Linked List based implementation of Queue ADT
Problem Statement / Aim / Objective
To implement the linked list based Queue ADT for a set of numbers (marks of students / set of
integers / scores by a individual players in certain number of innings). Write appropriate (following
set of) algorithms for handling the available data (set of numbers ) and to structure them (Data
structure)

1) Enqueue
2) Display
Write a C program to implement the given problem statement with separate
3) Dequeue functions for each algorithm.

4) ModifyFront / ModifyRear
5) PeekFront / PeekRear
6) isEmpty
7) Clear
8) etc.,
211
Algorithm for insertion (Enqueue) in Linked-List
based queue ADT
void ENQUEUE(int d){
temp=(struct node*)malloc(sizeof(struct node));
temp->data=d;
temp->next=NULL;
if(front==NULL){
front=rear=temp;
return;
}
rear->next=temp;
rear=temp;
} 212
Algorithm for displaying the contents of Linked-
List based Queue ADT
void display(){
if(front==NULL){
printf("\nSorry Queue is empty; Queue underflow");
return;
}
p=front;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
} 213
Algorithm for deletion (Dequeue) in Linked-List
based queue ADT - Return Data
int DEQUEUE(){
int x;
if(front==NULL){
printf("\nSorry Queue is empty:Queue underflow");
return;
}
x=front->data;
front=front->next;
return x;
} 214
Algorithm for deletion (Dequeue) in Linked-List
based queue ADT - Return Node
struct node* DEQUEUENode(){
if(front==NULL){
printf("\nSorry Queue is empty:Queue underflow");
return;
}
p=front;
front=front->next;
return p;
} 215
Worst Case Run-time complexity of Queue ADT
Algorithms
ADT Enqueue Dequeue Traversal Peek ModifyFront/ isEmpty
Type ModifyRear

Array O(1) O(1) O(N) O(1) O(1) O(1)


based
Linked O(1) O(1) O(N) O(1) O(1) O(1)
List-
based

216
1) Write an algorithm to POP the elements from a Stack ADT
and ENQUEUE those elements in a Queue ADT using
Linked-List based Implementation.

2) Write an algorithm to DEQUEUE the elements from a Queue


ADT and PUSH those elements in a Stack ADT using
Linked-List based Implementation.

217
Homework - 14/03/2024

1) Write an algorithm to POP the elements from two Stacks and


merge them in a single Queue using Linked-List based
Implementation.

2) Write an algorithm to DEQUEUE the elements from two


Queues and merge them in a single Stack using Linked-List
based Implementation.

218
Types of Queues

● Simple Queue
● Circular Queue
● Priority Queue
● Double Ended Queue (Not follows FIFO,
insertion/deletion can be done both in
begin and end)
219

End of Unit - II

220
UNIT -
III

Tree Data Structures

221
UNIT III
TREE DATA STRUCTURES
▷ Tree ADT
▷ Representation
▷ Traversals
▷ Binary Tree
▷ Expression trees
▷ Binary Search Tree
▷ AVL Trees
Tree ADT

▷ Tree ADT are a category of non-linear data


structures, in which each node may have more
than two neighbours.
▷ Every tree will have N nodes and N-1 edges.
▷ Top most node in a tree is called as a root node.
▷ Other nodes are children of the root node.
Terminologies in Tree ADT
1. Root 10. Siblings
2. Leaf 11. Parent
3. Edges 12. Child
4. Path 13. Grandparent
5. Subtree
14. Ancestors
6. Depth
7. Height 15. Descenders
8. Forest 16. Internal Nodes
9. Degree of a node 17. External Nodes
Terminologies in Tree ADT
1. Root - Top node in a tree
2. Leaf - Last nodes in a tree without any children
3. Edges - Connections between two nodes
4. Subtree - Distinct trees that can be formed from a tree
5. Depth - Number of edges between node ‘N’ and root node
(Depth of root node = 0)
6. Height - Number of edges between root node and node
‘N’(Height of leaf node=0)
Height of root node = Height of tree
7. Path - Sequence of nodes between two nodes
8. Forest - More number of trees
Terminologies in Tree ADT Cont…
9. Degree of a node - Number of children for a node
10. Siblings - Nodes with same parent
11. Parent - Immediate ancestor of a node
12. Child - Immediate descendent of a node
13. Grandparent - Ancestor of a node
14. Ancestors - For a leaf node, the intermediate nodes till root node
are ancestors
15. Descenders - For a root node, the intermediate nodes till leaf
node are descenders
16. Internal nodes - Nodes excluding the leaf nodes and root node
17. External nodes - All the leaf nodes and root nodes are external
nodes
Types of Tree Data Structures
1. A General Tree - each node can have any number of children
2. Binary Tree - each node can have maximum of 2 children
a. Binary Search Tree
b. AVL Tree
3. B-Tree
4. Splay Tree
5. Red-Black Tree
6. etc.,
Types of Binary Trees
In a binary tree each node can have maximum of 2 children
( 0 or 1 child or 2 children)
1) Perfect Binary Tree - all the levels are filled with nodes
2) Complete Binary Tree - not mandatory to fill all the
levels with nodes
3) Strict Binary Tree - nodes will have either 0 or 2 children
4) Skew Binary Tree - nodes will have either 0 or 1 child
a) Left Skew Binary Tree
b) Right Skew Binary Tree
Types of Binary Trees

229
Traversal in Binary Trees
● Process of visiting each nodes in a data structure at least once
(Ex:display)
● In trees traversal could be implemented in any of the following
mechanisms
1) Preorder - Process of visiting the node itself and then
recursively visiting children left to right. (Middle - Left - Right)
2) Postorder - Process of recursively visiting children left to right
before visiting the node itself (Left - Right - Middle)
3) Inorder - Process of recursively visiting the left children, then
the node itself and then recursively visiting the right children
(Left - Middle- Right )
4) Level order - Process of visiting the nodes level by level (No
recursion) 230
Binary Search Tree (BST)

231
Binary Search Tree (BST)
▷ BST are extended versions of binary trees, in which elements lesser
than the root nodes moves to the left sub-tree and the elements greater
than the root node moves to the right sub-tree.
▷ The first inserted element will be the root node.
▷ Linear cost of searching in linked list based linear data structure are
costly to implement.
▷ So, the non-linear BST data structure could make the search problem
easier as the data are arranged in sequential order (smaller values to
the left of root and larger values to the right of the root)
▷ BST may not always look balanced after insertion (depending on the
input sequence)
Homework - 21/03/2024

Insert the following sequences in a BST and perform all


four types of traversals.
1. G, H, F, D, A, B, S, X, O, Q
2. 45, 12, 3, 6 ,75, 12, 14, 56
3. M, P, X, O, Q, F, D, R, G, A, K
4. 20,17,23,14,32,8,12,41,6,9,13

233
Binary Search Tree implementation
Problem Statement / Aim / Objective
To implement the Binary Search Tree for a set of numbers (marks of students / set of
integers / scores by a individual players in certain number of innings). Write appropriate
(following set of) algorithms for handling the available data (set of numbers ) and to
structure them (Data structure)
1) Insert
2) Traversal
a) Preorder Write a C program to implement the given problem statement with separate
b) Postorder functions for each algorithm.
c) Inorder
d) Decendingorder
3) Delete
4) Search
5) Find Minimum
6) Find Maximum
7) Clear
8) etc., 234
Implementation of a Binary Search Tree ADT

//Node initialization
struct node{
int data;
struct node *left;
struct node *right;
} *root=NULL, *temp=NULL;
Algorithm for Node Creation

struct node* createnode(int d){


temp=(struct node*)malloc(sizeof(struct node));
temp->data=d;
temp->left=NULL;
temp->right=NULL;
return temp;
}
236
Algorithm for Insertion in a BST
struct node* insert(struct node *T, int d){
if(T==NULL)
T=createnode(d);
else if(d>T->data)
T->right=insert(T->right,d);
else if(d<T->data)
T->left=insert(T->left,d);
return T;
} 237
Algorithm for Preoder Traversal

void preorder(struct node *T){


if(T!=NULL){
printf("%d ",T->data); //M
preorder(T->left); //L
preorder(T->right); //R
}

238
Algorithm for Postorder Traversal

void postorder(struct node *T){


if(T!=NULL){
postorder(T->left); //L
postorder(T->right); //R
printf("%d ",T->data);//M
}
}
239
Algorithm for inorder Traversal

void inorder(struct node *T){


if(T!=NULL){
inorder(T->left); //L
printf("%d ",T->data);//M
inorder(T->right); //R
}
}
# 240
Algorithm for Decending order
Traversal
void decendingorder(struct node* T){
if(T!=NULL){
decendingorder(T->right); //R
printf("%d ",T->data); //M
decendingorder(T->left); //L
}
}
241
Algorithm for Finding the Minimum
Element node

struct node *minimum(struct node* T){


while(T->left!=NULL)
T=T->left;
return T;
}
242
Algorithm for Finding the
Maximum Element node

struct node *maximum(struct node* T){


while(T->right!=NULL)
T=T->right;
return T;
}

243
Deletion in a BST
Deletion of nodes / elements in a BST may happen under any of the following 3
cases of delete operation
Deletion of a node with
Case 1: ‘0’ Child (Leaf nodes)
Case 2: ‘1’ Child
Case 3: ‘2’ Children - We have to reduce the problem statement to either case 1
or case 2.
▷ Option 1: Pick max value node in left subtree, duplicate it in the data of the
node to be removed. Now the problem reduces to case 1 / case 2.
▷ Option 2: Pick min value node in left subtree, duplicate it in the data of the
node to be removed. Now the problem reduces to case 1 / case 2.
Algorithm for Deletion in BST
struct node *Delete(struct node *T, int d){
//First search the node to be deleted
if (T==NULL)
return T;
else if(d>T->data)
T->right=Delete(T->right,d);
else if(d<T->data)
T->left=Delete(T->left,d);
//Node to be deleted have been located at this point - Now delete
else{ //Case 1: 0 child
if(T->left ==NULL && T->right ==NULL){
T=NULL;
free(T);
}
Algorithm for Deletion in BST Cont…
//Case 2: 1 child (right child only)
else if(T->left==NULL ){
temp=T;
T=T->right;
free (temp);
}
//Case 2: 1 child (left child only)
else if(T->right==NULL ){
temp=T;
T=T->left;
free (temp);
}
Algorithm for Deletion in BST Cont…
//Case 3: 2 children (i.e T->left !=NULL && T->right!+NULL)
else {
temp=minimum(T->right); //find min element node in right subtree
T->data=temp->data; //duplicate the data node to be removed
//Now the problem will be reduced to case 1 or case 2
//Now remove the duplicate element by calling the algorithm again
T->right=Delete(T->right,T->data);
}
}
return T;
}
Algorithm for Searching in BST

struct node *Search(struct node *T, int d){


if (T == NULL || T->data == d)
return T;
if (d > T->data)
return Search(T->right, d);
else
return Search(T->left, d);
}
248
Run time and Space Complexity of
BST Algorithms
Complexity Search Insert Delete Traversal

Worst case O(N) O(N) O(N) O(N)

Average case O(Log N ) O(Log N) O(Log N) O(N)

Best case O(1) O(Log N) O(Log N) O(N)


Homework - 27/03/2024
Use the program in the link to include the following 5 algorithms of BST (use separate functions for
each algorithm) in the BST Program. Send the completed homework in a single file with the following
5 algorithms included.

https://classroom.google.com/c/NjU4MTE3NDA3NTQ4/m/NjU5ODMxNDgyNTg5/details

1) Write an algorithm to find the average of the root node element, minimum element, and maximum
element in a BST
2) Write an algorithm to delete the maximum element in a BST
3) Write an algorithm to double all the node values in a BST
4) Write an algorithm for counting the number of nodes in a BST
5) Write an algorithm to find the average of all the elements in all nodes in a BST.

250
Expression Trees

251
Expression Trees

● Evaluation of expressions are carried out by the compiler


using binary trees
● In a binary tree, the internal nodes will have the operators
and the external (leaf) nodes will have the operands
● Binary trees are used for interpreting the expressions
○ Directly on infix expression
○ Converting infix to postfix expression.

252
Expression Trees
(Examples)

253
AVL Tree

254
AVL Trees

▷ AVL Trees are named after Adelson, Velskii and Landis


▷ AVL Trees are balanced BST.
▷ Drawback of BST: Based on the sequence of inputs the tree
may not be balanced under few cases (Ex:Skew Trees)
▷ AVL Trees converts such input sequences into balanced
trees.
▷ Unbalanced conditions are observed from the balance factor
(based on height of subtree)
Balance Factor

▷ Balance Factor = Height of left subtree - Height of right


subtree
BF=Htl - Htr
|BF|=|Htl - Htr| <=1
▷ The value of BF for every node should be either {-1, 0,or 1} to
maintain the balance condition.
-

-
257

You might also like