0% found this document useful (0 votes)
27 views129 pages

DS - Unit - 2

Data structures are essential for organizing, storing, and manipulating data in programming, with types including linear, static, dynamic, and non-linear structures. Recursion, a method where a function calls itself, is crucial for solving problems by breaking them into smaller subproblems, and it can be direct or indirect. Understanding recursion's characteristics, base cases, and memory allocation is vital for effective programming.

Uploaded by

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

DS - Unit - 2

Data structures are essential for organizing, storing, and manipulating data in programming, with types including linear, static, dynamic, and non-linear structures. Recursion, a method where a function calls itself, is crucial for solving problems by breaking them into smaller subproblems, and it can be direct or indirect. Understanding recursion's characteristics, base cases, and memory allocation is vital for effective programming.

Uploaded by

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

AITAM Data Structures MCA

UNIT – 2
DATA STRUCTURES
Definitio
n:
Data structures are the fundamental building blocks of computer programming. They
define how data is organized, stored, and manipulated within a program.
Understanding data structures is very important for developing efficient and effective
algorithms.

What is Data Structure?

A data structure is a storage that is used to store and organize data. It is a way of
arranging data on a computer so that it can be accessed and updated efficiently.

A data structure is not only used for organizing the data. It is also used for processing,
retrieving, and storing data. There are different basic and advanced types of data
structures that are used in almost every program or software system that has been
developed.

Types of Data Structure

1. Linear Data Structure: Data structure in which data elements are arranged
sequentially or linearly, where each element is attached to its previous and next
adjacent elements, is called a linear data structure.

Example: Array, Stack, Queue, Linked List, etc.

Jayavardhanarao Sahukaru @ aitam 1


AITAM Data Structures MCA

2.Static Data Structure: Static data structure has a fixed memory size. It is easier
to access the elements in a static data structure.

Example: array.

Jayavardhanarao Sahukaru @ aitam 2


AITAM Data Structures MCA

3. Dynamic Data Structure: In dynamic data structure, the size is not fixed. It can
be randomly updated during the runtime which may be considered efficient concerning
the memory (space) complexity of the code.

Example: Queue, Stack, etc.

4.Non-Linear Data Structure: Data structures where data elements are not placed
sequentially or linearly are called non-linear data structures. In a non-linear data
structure, we can’t traverse all the elements in a single run only.

Examples: Trees and Graphs.

Recursive Algorithms
Recursive issues are common in competitive programming. And you will first develop
recursive logic for them before attempting to tackle these issues utilizing various
programming paradigms. Recursive thinking is a crucial part of programming. It helps
you divide complicated tasks into simpler ones. As a result, it is often used in practically
all programming languages.

What is Recursion?

Recursion is the action of a function calling itself either directly or indirectly, and the
associated function is known as a recursive function. A recursive method can be used
to tackle some issues with relative ease. Towers of Hanoi (TOH), in
order/preorder/postorder tree traversals, DFS of Graph, etc., are a few examples of these
issues. By calling a duplicate of itself and resolving the original problem's smaller
subproblems, a recursive function solves a specific problem. As and when necessary,
many additional recursive calls can be produced. It is crucial to understand that we
must present a specific situation to stop this recursion process. Therefore, each time,
the function calls itself a simplified version of the initial issue.

A recursive algorithm calls itself with smaller input values and, after performing basic
operations on the returned value for the minor input, provides the result for the current input.
A recursive method can solve a problem if smaller versions of the same problem can be
solved by applying solutions to them, and the smaller versions decrease to easily
solvable examples.

You will split the provided problem statement into two pieces to construct a recursive
algorithm. The primary case is the first, and the recursive step is the second.

Base Case: This is the simplest possible solution to the issue, consisting only of a
condition that ends the recursive function. When a specific condition is satisfied, the
result is evaluated in this base case.

Recursive Step: It calculates the outcome by making repeated calls to the same
function but with more minor or straightforward inputs.

Recursion Required for:

Jayavardhanarao Sahukaru @ aitam 3


AITAM Data Structures MCA

Recursion is a fantastic approach that allows us to shorten our code and simplify
understanding and writing. Compared to the iteration approach, it offers a few benefits
that will be covered later. Recursion

Jayavardhanarao Sahukaru @ aitam 4


AITAM Data Structures MCA

is one of the finest ways to complete a work that its related subtasks may describe. The
factorial of a number, for instance.

Characteristics of Recursion

Recursion's characteristics include:

 Repeating the same actions with different inputs.


 To make the issue smaller at each phase, we experiment with smaller inputs.
 A base condition must stop the recursion; otherwise, an infinite loop would result.

Steps in an Algorithm

The following algorithmic steps are used to implement recursion in a function:

Step 1: Establish a primary case. Choose the most straightforward situation for which
the answer is obvious or trivial. This is the recursion's halting condition, which stops the
function from indefinitely calling itself.

Define a recursive case in step two: Describe the issue in terms of its smaller
counterparts. Recursively calling the function will allow you to solve each subproblem
by breaking the problem up into smaller versions of itself.

Step 3: Verify that the recursion ends: Make sure the recursive code does not go into
an infinite loop and ultimately reaches the base case.

Step 4: Combine the solutions. To answer the main problem, combine the solutions
to the subproblems.

An Interpretation in Mathematics

Let's look at a situation where a programmer has to get the sum of the first n natural
numbers. There are a few methods for achieving this, but the easiest one is to add the
integers from 1 to n. Therefore, the function is represented mathematically as follows:
approach(1) - Simply adding one at a time f(n) = 1 + 2 + 3 + + n yet there is another
way to describe this: approach(2) - Recursive addition f(n) = 1
n=1 f(n) = n + f(n-1) n>1

The only difference between approaches (1) and (2) is that in approach (2), the function
"f()" is called within the function. This phenomenon is known as recursion, and the
function that contains recursion is known as a recursive function. In the end, this is an
excellent tool for programmers to code some problems more straightforwardly and
effectively.

Recursive functions are stored in memory in what manner?

Recursion consumes additional memory because the recursive function adds to the
stack with each call and stores the items there until the call is concluded. Like the stack
data structure, the recursive function uses the LIFO (LAST IN FIRST OUT) structure.

Jayavardhanarao Sahukaru @ aitam 5


AITAM Data Structures MCA

What defines the recursive base condition?

The base case solution is given in the recursive program, and the more significant
problem's solution is given in terms of more minor issues.

int fact(int n)

if (n < = 1) // base

case return 1;

else

return n*fact(n-1);

The base case for n = 1 is described in the example mentioned earlier, and the more
excellent value of a number may be addressed by downsizing it until the base case is
attained.

How is recursion used to tackle a specific problem?

The goal is to break a more significant problem down into a more minor one, then add a
base condition or conditions to stop the recursion. For instance, if we know the factorial
of (n-1), we may compute factorial n. Factorial's primary case would be n = 0. If n
equals 0, we return 1.

Why does recursion lead to a stack overflow error?

The stack overflow issue may occur if the base case is not reached or defined. To further
grasp this, let's look at an example.

int fact(int n)
{
// wrong base case (it may cause
// stack
overflow). if (n
== 100)
return
1; else
return n*fact(n-1);
}

If fact(10) is called, fact(9), fact(8), fact(7), and so forth will also be called, but the total will
always be
100. The primary case still needs to be achieved. A stack overflow fault will occur if these
functions on the stack fill up all available memory.

What distinguishes direct from indirect recursion?

Jayavardhanarao Sahukaru @ aitam 6


AITAM Data Structures MCA

If a function calls another function named fun, that function is said to be direct recursive.
If a function fun calls another function, like fun_new, and fun_new calls fun either directly or
indirectly, that function

Jayavardhanarao Sahukaru @ aitam 7


AITAM Data Structures MCA

is said to be indirectly recursive. Table 1 presents an illustration of the distinction between


direct and indirect recursion.

// An example of direct recursion

void directRecFun()
{
// Some code...
directRecFun();
// Some code...
}
// An example of indirect
recursion void
indirectRecFun1()
{
// Some code...

indirectRecFun2();

// Some code...
}
void indirectRecFun2()
{
// Some code...

indirectRecFun1

();

// Some code...
}

What distinguishes tailed from non-tailed recursion?

When a recursive call is the function's final action, it is said to be tail recursive. For more
information, see the article on tail recursion.

How does recursion distribute memory to various function calls?

Any function is given memory on the stack when called from main(). Every time a
recursive function calls itself, a new copy of the local variables is made, and memory is
allocated for the called function on top of the memory allocated for the calling
function. When the function reaches the base case, memory is released, and the
process continues, delivering its value to the function from which it was called.

Allocation of Memory for Recursive Method

The function is generated in fresh stack memory copies with each recursive call. The copy
is removed from storage once the operation returns some data. Because all
arguments and other variables specified inside functions are retained on the stack,
Jayavardhanarao Sahukaru @ aitam 8
AITAM Data Structures MCA

each recursive call retains a separate stack. The stack is removed after the value from
the proper function is returned.

Jayavardhanarao Sahukaru @ aitam 9


AITAM Data Structures MCA

Regarding resolving and tracking the values at each recursive call, recursion is
reasonably tricky. Thus, You must keep track of the stack's contents and the variables'
values. Examine the following example to learn more about how recursive functions
allocate memory.

//Fibonacci program recursive Function

int Fib(int num)


{
if ( num
== 0 )
return 0;
else if ( num
== 1 ) return
1;
else
return ( Fib(num-1) + Fib(num - 2) );
}

//Let's say we want to calculate the Fibonacci number

for n=5 Fib(5)

Now consider the following recursive Fibonacci algorithm for n = 5. All stacks are first
saved before printing the matching value of n until n equals zero. The stacks are
eliminated one at a time once the termination condition is met by returning 0 to the
calling stack. Look at the diagram below to comprehend the call stack hierarchy.

Types of Recursions in C
This section will discuss the different types of recursions in the C programming
language. Recursion is the process in which a function calls itself up to n-number of
Jayavardhanarao Sahukaru @ aitam 10
AITAM Data Structures MCA

times. If a program allows the user to call a function inside the same function recursively,
the procedure is called a recursive call of the function. Furthermore, a recursive function
can call itself directly or indirectly in the same program.

Jayavardhanarao Sahukaru @ aitam 11


AITAM Data Structures MCA

Syntax of the Recursion function

void recursion ()
{
recursion(); // The recursive function calls itself inside the same function
}
int main ()
{
recursion (); // function call
}

In the above syntax, the main() function calls the recursion function only once. After that,
the recursion function calls itself up to the defined condition, and if the user doesn't define
the condition, it calls the same function infinite times.

Different types of the recursion

The following are the types of the recursion in C programming language, as follows:

 Direct Recursion
 Indirect Recursion
 Tail Recursion
 No Tail/ Head Recursion
 Linear recursion
 Tree Recursion
Direct Recursion

When a function calls itself within the same function repeatedly, it is called the direct
recursion.

Structure of the direct recursion

fun()
{
// write some
code fun();
// some code
}
In the above structure of the direct recursion, the outer fun() function recursively calls the
inner fun() function, and this type of recursion is called the direct recursion.

Eg: write a program to(Generate Fibonacci series)demonstrate direct recursion in C


programming language.

#include<stdio.h
> int fibo_num
(int i)
{

Jayavardhanarao Sahukaru @ aitam 12


AITAM Data Structures MCA

// if the num i is equal to 0, return


0; if ( i == 0)

Jayavardhanarao Sahukaru @ aitam 13


AITAM Data Structures MCA

{
return 0;
}
if ( i == 1)
{
return 1;
}
return fibo_num (i - 1) + fibonacci (i -2);
}
int main ()
{
int i;
// use for loop to get the first 10 fibonacci
series for ( i = 0; i < 10; i++)
{
printf (" %d \t ", fibo_num (i));
}
return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

Indirect Recursion

When a function is mutually called by another function in a circular manner, the function
is called an indirect recursion function.

Structure of the indirect recursion

fun1()
{
// write some
code fun2()
}
fun2()
{
// write some code
fun3()
// write some code
}
fun3()
{
// write some code
fun1()
}

Jayavardhanarao Sahukaru @ aitam 14


AITAM Data Structures MCA

In this structure, there are four functions, fun1(), fun2(), fun3(). When the fun1() function is
executed, it calls the fun2() for its execution. And then, the fun2() function starts its
execution calls the fun3() function. In this way, each function leads to another function
to makes their execution circularly. And this type of approach is called indirect
recursion.

Eg: write a program to demonstrate the indirect recursion in C programming

language. #include <stdio.h>


// declaration of the odd and even() function
void odd(); // Add 1 when the function is odd()
void even(); // Subtract 1 when the function
is even int num = 1; // global variable
void odd ()
{
// if statement check and execute the block till n is less than
equal to 10 if (num <= 10)
{
printf (" %d ", num + 1); // print a number by
adding 1 num++; // increment by 1
even(); // invoke the even function
}
return;
}
void even ()
{
// if block check the condition that n is less than
equal to 10 if ( num <= 10)
{
printf (" %d ", num - 1); // print a number by
subtracting 1 num++;
odd(); // call the odd() function
}
return;
}
int main ()
{
odd(); // main call the odd() function at once
return 0;
}

Output

2 1 4 3 6 5 8 7 10 9

Tail Recursion

A recursive function is called the tail-recursive if the function makes recursive calling
itself, and that recursive call is the last statement executes by the function. After that, there is
no function or statement is left to call the recursive function.
Jayavardhanarao Sahukaru @ aitam 15
AITAM Data Structures MCA

Eg: write a program to demonstrate the tail recursion in C programming

language. #include <stdio.h>


// function definition
void fun1( int num)
{
// if block check the
condition if (num == 0)
return;
else
printf ("\n Number is: %d", num); // print the number
return fun1 (num - 1); // recursive call at the end in the fun() function
}
int main ()
{
fun1(7); // pass 7 as integer
argument return 0;
}

Output

Number is: 7
Number is: 6
Number is: 5
Number is: 4
Number is: 3
Number is: 2
Number is: 1

Non-Tail / Head Recursion

A function is called the non-tail or head recursive if a function makes a recursive call itself, the
recursive call will be the first statement in the function. It means there should be no
statement or operation is called before the recursive calls. Furthermore, the head
recursive does not perform any operation at the time of recursive calling. Instead, all
operations are done at the return time.

Eg: write a program to demonstrate the Head/Non-Tail recursion in C

programming language. #include <stdio.h>


void head_fun (int num)
{
if ( num > 0 )
{
// Here the head_fun() is the first statement to be called
head_fun (num -1);
printf (" %d", num);
}
}
Jayavardhanarao Sahukaru @ aitam 16
AITAM Data Structures MCA

int main ()
{
int a = 5;
printf (" Use of Non-Tail/Head Recursive function \n");
head_fun (a); // function calling
return 0;
}

Output

Use of Non-Tail/Head Recursive


function 1 2 3 4 5

Linear Recursion

A function is called the linear recursive if the function makes a single call to itself at
each time the function runs and grows linearly in proportion to the size of the problem.

Eg: write a program to demonstrate the linear Recursion in C programming

language. #include <stdio.h>


#define NUM 7
int rec_num( int *arr, int n)
{
if (n == 1)
{
return arr[0];
}
return Max_num (rec_num (arr, n-1), arr[n-1]);
}
// get the maximum
number int Max_num
(int n, int m)
{
if (n >
m)
return
n;
return m;
}
int main ()
{
// declare and initialize an array
int arr[NUM] = { 4, 8, 23, 19, 5, 35, 2};
int max = rec_num(arr, NUM); // call function
printf (" The maximum number is: %d\n", max); // print the largest number
}

Output

Jayavardhanarao Sahukaru @ aitam 17


AITAM Data Structures MCA

The maximum number is: 35

Jayavardhanarao Sahukaru @ aitam 18


AITAM Data Structures MCA

Tree Recursion

A function is called the tree recursion, in which the function makes more than one call to
itself within the recursive function.

Eg: write a program to demonstrate the tree recursion in C programming

language. #include <stdio.h>


// It is called multiple times inside the fibo_num function
int fibo_num (int num)
{
if (num <=
1) return
num;
return fibo_num (num - 1 ) + fibo_num(num - 2);
}
void main()
{
int num = 7;
printf (" Use of Tree Recursion: \n");
// print the number
printf (" The Fibonacci number is: %d", fibo_num(7));
}

Output

Use of Tree Recursion:


The Fibonacci number is: 13

Preliminaries of algorithms
What is an Algorithm?

An algorithm is a process or a set of rules required to perform calculations or some


other problem- solving operations especially by a computer. The formal definition of an
algorithm is that it contains the finite set of instructions which are being carried in a
specific order to perform the specific task. It is not the complete program or code; it is just a
solution (logic) of a problem, which can be represented either as an informal description
using a Flowchart or Pseudocode.

Characteristics of an Algorithm

The following are the characteristics of an algorithm:

 Input: An algorithm has some input values. We can pass 0 or some input value to
an algorithm.
 Output: We will get 1 or more output at the end of an algorithm.
 Unambiguity: An algorithm should be unambiguous which means that the
instructions in an algorithm should be clear and simple.
 Finiteness: An algorithm should have finiteness. Here, finiteness means that
Jayavardhanarao Sahukaru @ aitam 19
AITAM Data Structures MCA

the algorithm should contain a limited number of instructions, i.e., the


instructions should be countable.

Jayavardhanarao Sahukaru @ aitam 20


AITAM Data Structures MCA

 Effectiveness: An algorithm should be effective as each instruction in an


algorithm affects the overall process.
 Language independent: An algorithm must be language-independent so that
the instructions in an algorithm can be implemented in any of the languages with
the same output.
Dataflow of an Algorithm
 Problem: A problem can be a real-world problem or any instance from the real-
world problem for which we need to create a program or the set of instructions. The
set of instructions is known as an algorithm.
 Algorithm: An algorithm will be designed for a problem which is a step by step
procedure.
 Input: After designing an algorithm, the required and the desired inputs are
provided to the algorithm.
 Processing unit: The input will be given to the processing unit, and the
processing unit will produce the desired output.
 Output: The output is the outcome or the result of the program.
Why do we need Algorithms?
We need algorithms because of the following reasons:
 Scalability: It helps us to understand the scalability. When we have a big real-
world problem, we need to scale it down into small-small steps to easily analyze
the problem.
 Performance: The real-world is not easily broken down into smaller steps. If the
problem can be easily broken into smaller steps means that the problem is
feasible.
As an example, We will write an algorithm to add two numbers entered by the user. The
following are the steps required to add two numbers entered by the user:
 Step 1: Start
 Step 2: Declare three variables a, b, and sum.
 Step 3: Enter the values of a and b.
 Step 4: Add the values of a and b and store the result in the sum variable, i.e.,
sum=a+b.
 Step 5: Print sum
 Step 6: Stop
Factors of an Algorithm
The following are the factors that we need to consider for designing an algorithm:
 Modularity: If any problem is given and we can break that problem into small-
small modules or small-small steps, which is a basic definition of an algorithm, it
means that this feature has been perfectly designed for the algorithm.
 Correctness: The correctness of an algorithm is defined as when the given
inputs produce the desired output, which means that the algorithm has been
designed algorithm. The analysis of an algorithm has been done correctly.
 Maintainability: Here, maintainability means that the algorithm should be
designed in a very simple structured way so that when we redefine the algorithm,
no major change will be done in the algorithm.
 Functionality: It considers various logical steps to solve the real-world problem.
Jayavardhanarao Sahukaru @ aitam 21
AITAM Data Structures MCA

 Robustness: Robustness means that how an algorithm can clearly define our
problem.
 User-friendly: If the algorithm is not user-friendly, then the designer will not be able
to explain it to the programmer.

Jayavardhanarao Sahukaru @ aitam 22


AITAM Data Structures MCA

 Simplicity: If the algorithm is simple then it is easy to understand.


 Extensibility: If any other algorithm designer or programmer wants to use your
algorithm then it should be extensible.
Importance of Algorithms
1. Theoretical importance: When any real-world problem is given to us and we
break the problem into small-small modules. To break down the problem, we
should know all the theoretical aspects.
2. Practical importance: As we know that theory cannot be completed without
the practical implementation. So, the importance of algorithm can be considered
as both theoretical and practical.
Issues of Algorithms
The following are the issues that come while designing an algorithm:
o How to design algorithms: As we know that an algorithm is a step-by-step
procedure so we must follow some steps to design an algorithm.
o How to analyze algorithm
efficiency Approaches of
Algorithm
The following are the approaches used after considering both the theoretical and
practical importance of designing an algorithm:
o Brute force algorithm: The general logic structure is applied to design an
algorithm. It is also known as an exhaustive search algorithm that searches all
the possibilities to provide the required solution. Such algorithms are of two
types:
o Optimizing: Finding all the solutions of a problem and then take out the
best solution or if the value of the best solution is known then it will
terminate if the best solution is known.
o Sacrificing: As soon as the best solution is found, then it will stop.
o Divide and conquer: It is a very important implementation of an algorithm. It
allows you to design an algorithm in a step-by-step variation. It breaks down the
algorithm to solve the problem in different methods. It allows you to break down
the problem into different methods, and valid output is produced for the valid
input. This valid output is passed to some other function.
o Greedy algorithm: It is an algorithm paradigm that makes an optimal choice on
each iteration with the hope of getting the best solution. It is easy to implement
and has a faster execution time. But, there are very rare cases in which it
provides the optimal solution.
o Dynamic programming: It makes the algorithm more efficient by storing the
intermediate results. It follows five different steps to find the optimal solution for
the problem:
o It breaks down the problem into a subproblem to find the optimal solution.
o After breaking down the problem, it finds the optimal solution out of these
Jayavardhanarao Sahukaru @ aitam 23
AITAM Data Structures MCA

subproblems.
o Stores the result of the subproblems is known as memorization.
o Reuse the result so that it cannot be recomputed for the same subproblems.
o Finally, it computes the result of the complex program.

Jayavardhanarao Sahukaru @ aitam 24


AITAM Data Structures MCA

o Branch and Bound Algorithm: The branch and bound algorithm can be applied
to only integer programming problems. This approach divides all the sets of
feasible solutions into smaller subsets. These subsets are further evaluated to
find the best solution.
o Randomized Algorithm: As we have seen in a regular algorithm, we have
predefined input and required output. Those algorithms that have some defined
set of inputs and required output, and follow some described steps are known as
deterministic algorithms. What happens that when the random variable is
introduced in the randomized algorithm?. In a randomized algorithm, some
random bits are introduced by the algorithm and added in the input to produce the
output, which is random in nature. Randomized algorithms are simpler and
efficient than the deterministic algorithm.
o Backtracking: Backtracking is an algorithmic technique that solves the problem
recursively and removes the solution if it does not satisfy the constraints of a
problem.
The major categories of algorithms are given below:
o Sort: Algorithm developed for sorting the items in a certain order.
o Search: Algorithm developed for searching the items inside a data structure.
o Delete: Algorithm developed for deleting the existing element from the data
structure.
o Insert: Algorithm developed for inserting an item inside a data structure.
o Update: Algorithm developed for updating the existing element inside a data
structure.
Algorithm Analysis
The algorithm can be analyzed in two levels, i.e., first is before creating the algorithm,
and second is after creating the algorithm. The following are the two analysis of an
algorithm:
o Priori Analysis: Here, priori analysis is the theoretical analysis of an algorithm
which is done before implementing the algorithm. Various factors can be considered
before implementing the algorithm like processor speed, which has no effect on
the implementation part.
o Posterior Analysis: Here, posterior analysis is a practical analysis of an algorithm.
The practical analysis is achieved by implementing the algorithm using any
programming language. This analysis basically evaluate that how much running
time and space taken by the algorithm.
Algorithm Complexity
The performance of the algorithm can be measured in two factors:
o Time complexity: The time complexity of an algorithm is the amount of time
required to complete the execution. The time complexity of an algorithm is
denoted by the big O notation. Here, big O notation is the asymptotic notation to
represent the time complexity. The time complexity is mainly calculated by
counting the number of steps to finish the execution. Let's understand the time
Jayavardhanarao Sahukaru @ aitam 25
AITAM Data Structures MCA

complexity through an example.


sum=0;
// Suppose we have to calculate the sum of n
numbers. for i=1 to n
sum=sum+i;
// when the loop ends then sum holds the sum of the n
numbers return sum;

Jayavardhanarao Sahukaru @ aitam 26


AITAM Data Structures MCA

In the above code, the time complexity of the loop statement will be atleast n, and if
the value of n increases, then the time complexity also increases. While the complexity
of the code, i.e., return sum will be constant as its value is not dependent on the value
of n and will provide the result in one step only. We generally consider the worst-time
complexity as it is the maximum time taken for any given input size.
o Space complexity: An algorithm's space complexity is the amount of space
required to solve a problem and produce an output. Similar to the time
complexity, space complexity is also expressed in big O notation.
For an algorithm, the space is required for the following purposes:
1. To store program instructions
2. To store constant values
3. To store variable values
4. To track the function calls, jumping statements, etc.
Auxiliary space: The extra space required by the algorithm, excluding the input size, is
known as an auxiliary space. The space complexity considers both the spaces, i.e.,
auxiliary space, and space used by the input.
So,
Space complexity = Auxiliary space + Input size.
Types of Algorithms
The following are the types of algorithms:
o Search Algorithm
o Sort
Algorithm
Search
Algorithm
On each day, we search for something in our day to day life. Similarly, with the case of
computer, huge data is stored in a computer that whenever the user asks for any data
then the computer searches for that data in the memory and provides that data to the
user. There are mainly two techniques available to search the data in an array:
o Linear search
o Binary
search Linear
Search
Linear search is a very simple algorithm that starts searching for an element or a
value from the beginning of an array until the required element is found. It compares the
element to be searched with all the elements in an array, if the match is found, then it
returns the index of the element else it returns
-1. This algorithm can be implemented on the unsorted list.
Jayavardhanarao Sahukaru @ aitam 27
AITAM Data Structures MCA

Binary Search
A Binary algorithm is the simplest algorithm that searches the element very quickly. It is
used to search the element from the sorted list. The elements must be stored in
sequential order or the sorted manner

Jayavardhanarao Sahukaru @ aitam 28


AITAM Data Structures MCA

to implement the binary algorithm. Binary search cannot be implemented if the elements
are stored in a random manner. It is used to find the middle element of the list.
Sorting Algorithms
Sorting algorithms are used to rearrange the elements in an array or a given data
structure either in an ascending or descending order. The comparison operator decides
the new order of the elements.
Why do we need a sorting algorithm?
o An efficient sorting algorithm is required for optimizing the efficiency of other
algorithms like binary search algorithm as a binary search algorithm requires an array
to be sorted in a particular order, mainly in ascending order.
o It produces information in a sorted order, which is a human-readable format.
o Searching a particular element in a sorted list is faster than the unsorted list.

Asymptotic Analysis
As we know that data structure is a way of organizing the data efficiently and that efficiency is
measured either in terms of time or space. So, the ideal data structure is a structure
that occupies the least possible time to perform all its operation and the memory
space. Our focus would be on finding the time complexity rather than space complexity,
and by finding the time complexity, we can decide which data structure is the best for an
algorithm.
The main question arises in our mind that on what basis should we compare the time
complexity of data structures?. The time complexity can be compared based on
operations performed on them. Let's consider a simple example.
Suppose we have an array of 100 elements, and we want to insert a new element at
the beginning of the array. This becomes a very tedious task as we first need to shift the
elements towards the right, and we will add new element at the starting of the array.
Suppose we consider the linked list as a data structure to add the element at the beginning.
The linked list contains two parts, i.e., data and address of the next node. We simply add
the address of the first node in the new node, and head pointer will now point to the newly
added node. Therefore, we conclude that adding the data at the beginning of the linked
list is faster than the arrays. In this way, we can compare the data structures and
select the best possible data structure for performing the operations.
How to find the Time Complexity or running time for performing the operations?
The measuring of the actual running time is not practical at all. The running time to
perform any operation depends on the size of the input. Let's understand this
statement through a simple example.
Suppose we have an array of five elements, and we want to add a new element at the
beginning of the array. To achieve this, we need to shift each element towards right,
and suppose each element takes one unit of time. There are five elements, so five units
of time would be taken. Suppose there are 1000 elements in an array, then it takes 1000
units of time to shift. It concludes that time complexity depends upon the input size.
Therefore, if the input size is n, then f(n) is a function of n that denotes the time

Jayavardhanarao Sahukaru @ aitam 29


AITAM Data Structures MCA

complexity. How to calculate f(n)?


Calculating the value of f(n) for smaller programs is easy but for bigger programs, it's not
that easy. We can compare the data structures by comparing their f(n) values. We can
compare the data structures

Jayavardhanarao Sahukaru @ aitam 30


AITAM Data Structures MCA

by comparing their f(n) values. We will find the growth rate of f(n) because there might be a
possibility that one data structure for a smaller input size is better than the other one but
not for the larger sizes. Now, how to find f(n).
Let's look at a simple
example. f(n) = 5n2 + 6n
+ 12
where n is the number of instructions executed, and it depends on the size of
the input. When n=1

% of running time due to 5n2 = * 100 = 21.74%

% of running time due to 6n = * 100 = 26.09%

% of running time due to 12 = * 100 = 52.17%


From the above calculation, it is observed that most of the time is taken by 12. But, we
have to find the growth rate of f(n), we cannot say that the maximum amount of time is
taken by 12. Let's assume the different values of n to find the growth rate of f(n).

n 5n2 6n 12

1 21.74% 26.09% 52.17%

10 87.41% 10.49% 2.09%

100 98.79% 1.19% 0.02%

1000 99.88% 0.12% 0.0002%

As we can observe in the above table that with the increase in the value of n, the
running time of 5n2 increases while the running time of 6n and 12 also decreases. Therefore,
it is observed that for larger values of n, the squared term consumes almost 99% of the
time. As the n2 term is contributing most of the time, so we can eliminate the rest two
terms.
Therefore,
f(n) = 5n2
Here, we are getting the approximate time complexity whose result is very close to the
actual result. And this approximate measure of time complexity is known as an
Asymptotic complexity. Here, we are not calculating the exact running time, we are
eliminating the unnecessary terms, and we are just considering the term which is
taking most of the time.
In mathematical analysis, asymptotic analysis of algorithm is a method of defining the
mathematical boundation of its run-time performance. Using the asymptotic analysis,
Jayavardhanarao Sahukaru @ aitam 31
AITAM Data Structures MCA

we can easily conclude the average-case, best-case and worst-case scenario of an


algorithm.
It is used to mathematically calculate the running time of any operation inside an
algorithm.

Jayavardhanarao Sahukaru @ aitam 32


AITAM Data Structures MCA

Example: Running time of one operation is x(n) and for another operation, it is
calculated as f(n2). It refers to running time will increase linearly with an increase in 'n'
for the first operation, and running time will increase exponentially for the second
operation. Similarly, the running time of both operations will be the same if n is
significantly small.
Usually, the time required by an algorithm comes under three types:
Worst case: It defines the input for which the algorithm takes a huge time.
Average case: It takes average time for the program execution.
Best case: It defines the input for which the algorithm takes the
lowest time Asymptotic Notations
The commonly used asymptotic notations used for calculating the running time
complexity of an algorithm is given below:
o Big oh Notation (?)
o Omega Notation (Ω)
o Theta Notation
(θ) Big oh Notation
(O)
o Big O notation is an asymptotic notation that measures the performance of an
algorithm by simply providing the order of growth of the function.
o This notation provides an upper bound on a function which ensures that the
function never grows faster than the upper bound. So, it gives the least upper
bound on a function so that the function never grows faster than this upper
bound.
It is the formal way to express the upper boundary of an algorithm running time. It
measures the worst case of time complexity or the algorithm's longest amount of time
to complete its operation. It is represented as shown below:

For example:
If f(n) and g(n) are the two functions defined for positive integers,
then f(n) = O(g(n)) as f(n) is big oh of g(n) or f(n) is on the order of g(n)) if there
Jayavardhanarao Sahukaru @ aitam 33
AITAM Data Structures MCA

exists constants c and no such that:


f(n)≤c.g(n) for all n≥no

Jayavardhanarao Sahukaru @ aitam 34


AITAM Data Structures MCA

This implies that f(n) does not grow faster than g(n), or g(n) is an upper bound on the
function f(n). In this case, we are calculating the growth rate of the function which
eventually calculates the worst time complexity of a function, i.e., how worst an
algorithm can perform.
Let's understand through examples
Example 1: f(n)=2n+3 , g(n)=n
Now, we have to find Is f(n)=O(g(n))?
To check f(n)=O(g(n)), it must satisfy the given condition:
f(n)<=c.g(n)
First, we will replace f(n) by 2n+3 and g(n)
by n. 2n+3 <= c.n
Let's assume c=5, n=1
then 2*1+3<=5*1
5<=5
For n=1, the above condition is
true. If n=2
2*2+3<=5*2
7<=10
For n=2, the above condition is true.
We know that for any value of n, it will satisfy the above condition, i.e., 2n+3<=c.n. If
the value of c is equal to 5, then it will satisfy the condition 2n+3<=c.n. We can take any
value of n starting from 1, it will always satisfy. Therefore, we can say that for some
constants c and for some constants n0, it will always satisfy 2n+3<=c.n. As it is satisfying
the above condition, so f(n) is big oh of g(n) or we can say that f(n) grows linearly.
Therefore, it concludes that c.g(n) is the upper bound of the f(n). It can be represented
graphically as:

Jayavardhanarao Sahukaru @ aitam 35


AITAM Data Structures MCA

The idea of using big o notation is to give an upper bound of a particular function, and
eventually it leads to give a worst-time complexity. It provides an assurance that a
particular function does not behave suddenly as a quadratic or a cubic fashion, it just
behaves in a linear manner in a worst-case.
Omega Notation (Ω)
o It basically describes the best-case scenario which is opposite to the big o notation.
o It is the formal way to represent the lower bound of an algorithm's running time. It
measures the best amount of time an algorithm can possibly take to complete or
the best-case time complexity.
o It determines what is the fastest time that an algorithm can run.
If we required that an algorithm takes at least certain amount of time without using an upper
bound, we use big- Ω notation i.e. the Greek letter "omega". It is used to bound the growth of
running time for large input size.
If f(n) and g(n) are the two functions defined for positive integers,
then f(n) = Ω (g(n)) as f(n) is Omega of g(n) or f(n) is on the order of g(n)) if there
exists constants c and no such that:
f(n)>=c.g(n) for all n≥no
and c>0 Let's consider a
simple example. If f(n) =
2n+3, g(n) = n,
Is f(n)= Ω (g(n))?
It must satisfy the condition:
f(n)>=c.g(n)
To check the above condition, we first replace f(n) by 2n+3 and g(n) by n.
2n+3>=c*n
Suppose c=1
2n+3>=n (This equation will be true for any value of n
starting from 1). Therefore, it is proved that g(n) is big
omega of 2n+3 function.

Jayavardhanarao Sahukaru @ aitam 36


AITAM Data Structures MCA

Jayavardhanarao Sahukaru @ aitam 37


AITAM Data Structures MCA

As we can see in the above figure that g(n) function is the lower bound of the f(n)
function when the value of c is equal to 1. Therefore, this notation gives the fastest
running time. But, we are not more interested in finding the fastest running time, we are
interested in calculating the worst-case scenarios because we want to check our algorithm
for larger input that what is the worst time that it will take so that we can take further
decision in the further process.
Theta Notation (θ)
o The theta notation mainly describes the average case scenarios.
o It represents the realistic time complexity of an algorithm. Every time, an
algorithm does not perform worst or best, in real-world problems, algorithms
mainly fluctuate between the worst- case and best-case, and this gives us the
average case of the algorithm.
o Big theta is mainly used when the value of worst-case and the best-case is same.
o It is the formal way to express both the upper bound and lower bound of an
algorithm running time.
Let's understand the big theta notation mathematically:
Let f(n) and g(n) be the functions of n where n is the steps required to execute the
program then:
f(n)= θg(n)
The above condition is satisfied only if when
c1.g(n)<=f(n)<=c2.g(n)
where the function is bounded by two limits, i.e., upper and lower limit, and f(n) comes in
between. The condition f(n)= θg(n) will be true if and only if c1.g(n) is less than or equal to
f(n) and c2.g(n) is greater than or equal to f(n). The graphical representation of theta
notation is given below:

Jayavardhanarao Sahukaru @ aitam 38


AITAM Data Structures MCA

Let's consider the same example


where f(n)=2n+3
g(n)=n
As c1.g(n) should be less than f(n) so c1 has to be 1 whereas c2.g(n) should be greater
than f(n) so c2 is equal to 5. The c1.g(n) is the lower limit of the of the f(n) while c2.g(n) is
the upper limit of the f(n).
c1.g(n)<=f(n)<=c2.g(n)
Replace g(n) by n and f(n) by
2n+3 c1.n <=2n+3<=c2.n
if c1=1, c2=2,
n=1 1*1
<=2*1+3
<=2*1
1 <= 5 <= 2 // for n=1, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
If n=2
1*2<=2*2+3<=2*2
2<=7<=4 // for n=2, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
Therefore, we can say that for any value of n, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n).
Hence, it is proved that f(n) is big theta of g(n). So, this is the average-case scenario
which provides the realistic time complexity.
Why we have three different asymptotic analysis?
As we know that big omega is for the best case, big oh is for the worst case while big
theta is for the average case. Now, we will find out the average, worst and the best case
of the linear search algorithm.
Suppose we have an array of n numbers, and we want to find the particular element in
an array using the linear search. In the linear search, every element is compared with
the searched element on each iteration. Suppose, if the match is found in a first iteration
only, then the best case would be Ω(1), if the element matches with the last element, i.e.,
nth element of the array then the worst case would be
O(n). The average case is the mid of the best and the worst-case, so it becomes θ(n/1).
The constant terms can be ignored in the time complexity so average case
would be θ(n).
So, three different analysis provide the proper bounding between the actual functions. Here,
bounding means that we have upper as well as lower limit which assures that the
algorithm will behave between these limits only, i.e., it will not go beyond these limits.
Common Asymptotic Notations

constant - ?(1)

Jayavardhanarao Sahukaru @ aitam 39


AITAM Data Structures MCA

linear - ?(n)

logarithmic - ?(log n)

n log n - ?(n log n)

exponential - 2?(n)

cubic - ?(n3)

polynomial - n?(1)

quadratic - ?(n2)

Linear Search
Searching is the process of finding some particular element in the list. If the element is
present in the list, then the process is called successful, and the process returns the
location of that element; otherwise, the search is called unsuccessful.

Two popular search methods are Linear Search and Binary Search. So, here we will
discuss the popular searching technique, i.e., Linear Search Algorithm.

Linear search is also called as sequential search algorithm. It is the simplest


searching algorithm. In Linear search, we simply traverse the list completely and match
each element of the list with the item whose location is to be found. If the match is found,
then the location of the item is returned; otherwise, the algorithm returns NULL.

It is widely used to search an element from the unordered list, i.e., the list in which items are
not sorted. The worst-case time complexity of linear search is O(n).

The steps used in the implementation of Linear Search are listed as follows -

o First, we have to traverse the array elements using a for loop.

o In each iteration of for loop, compare the search element with the current array
element, and -

o If the element matches, then return the index of the corresponding array
element.

o If the element does not match, then move to the next element.

o If there is no match or the search element is not present in the given array, return -
1.

Jayavardhanarao Sahukaru @ aitam 40


AITAM Data Structures MCA

Algorithm
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' is the

value to search Step 1: set pos = -1

Step 2: set i = 1

Step 3: repeat step 4 while

i <= n Step 4: if a[i] ==

val

Jayavardhanarao Sahukaru @ aitam 41


AITAM Data Structures MCA

set pos =

i print

pos go to

step 6

[end of if]

set ii = i

+1

[end of loop]

Step 5: if pos = -1

print "value is not present in the

array " [end of if]

Step 6: exit

Working of Linear search


Let the elements of array are -

Let the element to be searched is K = 41

Now, start from the first element and compare K with each element of the array.

The value of K, i.e., 41, is not matched with the first element of the array. So,
move to the next element. And follow the same process until the respective
element is found.

Jayavardhanarao Sahukaru @ aitam 42


AITAM Data Structures MCA

Now, the element to be searched is found. So algorithm will return the index of the
element matched.

Linear Search complexity

o Best Case Complexity - In Linear search, best case occurs when the element
we are finding is at the first position of the array. The best-case time complexity
of linear search is O(1).

o Average Case Complexity - The average case time complexity of linear search is
O(n).

o Worst Case Complexity - In Linear search, the worst case occurs when the
element we are looking is present at the end of the array. The worst-case in
Jayavardhanarao Sahukaru @ aitam 43
AITAM Data Structures MCA

linear search could be when the target element is not present in the given array,
and we have to traverse the entire array. The worst-case time complexity of
linear search is O(n).

Jayavardhanarao Sahukaru @ aitam 44


AITAM Data Structures MCA

The time complexity of linear search is O(n) because every element in the array is
compared only once.

o The space complexity of linear search is O(1).

Implementation of Linear Search


#include <stdio.h>
int linearSearch(int a[], int n, int val) {
// Going through array
sequencially for (int i = 0; i <
n; i++)
{
if (a[i] ==
val) return
i+1;
}
return -1;
}
int main() {
int a[] = {70, 40, 30, 11, 57, 41, 25, 14, 52}; // given
array int val = 41; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of
array int res = linearSearch(a, n, val); //
Store result printf("The elements of the
array are - ");
for (int i = 0; i < n; i+
+) printf("%d ",
a[i]);
printf("\nElement to be searched is -
%d", val); if (res == -1)
printf("\nElement is not present in the
array"); else
printf("\nElement is present at %d position of array",
res); return 0;
}

Output:

Jayavardhanarao Sahukaru @ aitam 45


AITAM Data Structures MCA

Implementation of Linear Search using recursion


#include <stdio.h>
// Define a function to perform the linear
search int linearSearch(int arr[], int size,
int key)
{
// If the size of the array is zero,
return -1 if (size == 0) {
return -1;
}
// Check if the element at the current index
// is equal to the key
if (arr[size - 1] == key) {
// If equal, return the index
return size - 1;
}
// If not equal, call the function again
// with the size reduced by 1
return linearSearch(arr, size - 1, key);
}
// Driver code
int main()
{
int arr[] = { 5, 15, 6, 9, 4 };
int key =
4; int
index
= linearSearch(arr, sizeof(arr) / sizeof(int),
key); if (index == -1) {
printf("Key not found in the array.\n");
}
else {
printf("The element %d is found at %d index of
the " "given array \n",
key, index);
}
return 0;
}

Output:

Jayavardhanarao Sahukaru @ aitam 46


AITAM Data Structures MCA

Binary Search
Searching is the process of finding some particular element in the list. If the element is
present in the list, then the process is called successful, and the process returns the
location of that element. Otherwise, the search is called unsuccessful.

Linear Search and Binary Search are the two popular searching techniques. Here we
will discuss the Binary Search Algorithm.

Binary search is the search technique that works efficiently on sorted lists. Hence, to
search an element into some list using the binary search technique, we must ensure
that the list is sorted.

Binary search follows the divide and conquer approach in which the list is divided into
two halves, and the item is compared with the middle element of the list. If the match is
found then, the location of the middle element is returned. Otherwise, we search into
either of the halves depending upon the result produced through the match.

NOTE: Binary search can be implemented on sorted array elements. If the list
elements are not arranged in a sorted manner, we have first to sort them.

Algorithm
Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound' is
the index of the first array element, 'upper_bound' is the index of the last array element,
'val' is the value to search

Step 1: set beg = lower_bound, end = upper_bound,


pos = - 1 Step 2: repeat steps 3 and 4 while beg
<=end
Step 3: set mid = (beg +
end)/2 Step 4: if a[mid] =
val
set pos =
mid print
pos
go to step 6
else if a[mid] >
val set end =
mid - 1 else
set beg = mid
+ 1 [end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the
array" [end of if]
Step 6: exit

Working of Binary search

Jayavardhanarao Sahukaru @ aitam 47


AITAM Data Structures MCA

To understand the working of the Binary search algorithm, let's take a sorted array. It will
be easy to understand the working of Binary search with an example.

Jayavardhanarao Sahukaru @ aitam 48


AITAM Data Structures MCA

There are two methods to implement the binary search algorithm -

o Iterative method

o Recursive method

The recursive method of binary search follows the divide and conquer

approach. Let the elements of array are -

Let the element to search is, K = 56

We have to use the below formula to calculate the mid of the array -

1. mid = (beg +

end)/2 So, in the given

array - beg = 0

end = 8

mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.

Now, the element to search is found. So algorithm will return the index of the element

matched. Binary Search complexity.

Jayavardhanarao Sahukaru @ aitam 49


AITAM Data Structures MCA

o Best Case Complexity - In Binary search, best case occurs when the element to
search is found in first comparison, i.e., when the first middle element itself is the
element to be searched. The best-case time complexity of Binary search is O(1).

o Average Case Complexity - The average case time complexity of Binary search
is O(logn).

o Worst Case Complexity - In Binary search, the worst case occurs, when we
have to keep reducing the search space till it has only one element. The worst-case
time complexity of Binary search is O(logn).

Implementation of Binary Search


#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at
middle */ if(a[mid] == val)
{
return mid+1;
}
/* if the item to be searched is smaller than middle, then it can only be in left
subarray */
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/* if the item to be searched is greater than middle, then it can only be in right
subarray */
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
Jayavardhanarao Sahukaru @ aitam 50
AITAM Data Structures MCA

int main() {
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70}; // given array

Jayavardhanarao Sahukaru @ aitam 51


AITAM Data Structures MCA

int val = 40; // value to be searched


int n = sizeof(a) / sizeof(a[0]); // size of array
int res = binarySearch(a, 0, n-1, val); // Store
result printf("The elements of the array are
- ");
for (int i = 0; i < n; i+
+) printf("%d ",
a[i]);
printf("\nElement to be searched is -
%d", val); if (res == -1)
printf("\nElement is not present in the
array"); else
printf("\nElement is present at %d position of array",
res); return 0;
}

Output:

Implementation of Binary Search using recursion


// C program to implement binary search using

recursion #include <stdio.h>


int binarySearch(int arr[], int left, int right, int key) {
// checking if there are elements in the
subarray if (right >= left) {
// calculating mid point
int mid = left + (right - left) / 2;
// If the key is present at the middle
itself if (arr[mid] == key)
return mid;
// If key is smaller than arr[mid], then it can only
// be present in left
subarray if (arr[mid] >
key) {
return binarySearch(arr, left, mid - 1, key);
}
// Else the key can only be present in right
// subarray
return binarySearch(arr, mid + 1, right, key);
}
// We reach here when element is not present in
array return -1;
}
int main(void) {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
Jayavardhanarao Sahukaru @ aitam 52
AITAM Data Structures MCA

int size = sizeof(arr) / sizeof(arr[0]);


// element to be
searched int key = 23;

Jayavardhanarao Sahukaru @ aitam 53


AITAM Data Structures MCA

int index = binarySearch(arr, 0, size - 1,


key); if (index == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", index);
}
return 0;
}

Output:

Jayavardhanarao Sahukaru @ aitam 54


AITAM Data Structures MCA

Linked List
What is Linked
List?
A linked list is a linear data structure which can store a collection of "nodes" connected
via links i.e. pointers. Linked lists nodes are not stored at a contiguous location, rather
they are linked using pointers to the different memory locations. A node consists of the
data value and a pointer to the address of the next node within the linked list.

A linked list is a dynamic linear data structure whose memory size can be allocated or de-
allocated at run time based on the operation insertion or deletion, this helps in using
system memory efficiently. Linked lists can be used to implement various data
structures like a stack, queue, graph, hash maps, etc.

A linked list starts with a head node which points to the first node. Every node consists
of data which holds the actual data (value) associated with the node and a next
pointer which holds the memory address of the next node in the linked list. The last
node is called the tail node in the list which points to null indicating the end of the list.

Linked Lists vs Arrays


In the case of arrays, the size is given at the time of creation and so arrays are of fixed
length whereas Linked lists are dynamic in size and any number of nodes can be added
in the linked lists dynamically. An array can accommodate similar types of data types
whereas linked lists can store various nodes of different data types.

Types of Linked List


The following are the various types of linked list.

Singly Linked Lists

Singly linked lists contain two "buckets" in one node; one bucket holds the data, and
the other bucket holds the address of the next node of the list. Traversals can be done
in one direction only as there is only a single link between two nodes of the same list.

Doubly Linked Lists

Doubly Linked Lists contain three "buckets" in one node; one bucket holds the data,
and the other buckets hold the addresses of the previous and next nodes in the list. The

Jayavardhanarao Sahukaru @ aitam 55


AITAM Data Structures MCA

list is traversed twice as the nodes in the list are connected to each other from both
sides.

Jayavardhanarao Sahukaru @ aitam 56


AITAM Data Structures MCA

Circular Linked Lists

Circular linked lists can exist in both singly linked list and doubly linked list.

Since the last node and the first node of the circular linked list are connected, the
traversal in this linked list will go on forever until it is broken.

Basic Operations in Linked List

The basic operations in the linked lists are insertion, deletion, searching, display, and
deleting an element at a given key. These operations are performed on Singly Linked
Lists as given below –

 Insertion − Adds an element at the beginning of the list.


 Deletion − Deletes an element at the beginning of the list.
 Display − Displays the complete list.
 Search − Searches an element using the given key.
 Delete − Deletes an element using the given key.

Linked List - Insertion Operation

Adding a new node in the linked list is a more than one step activity. First, create a node
using the same structure and find the location where it has to be inserted.

Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C


(RightNode). Then point B.next to C −

Jayavardhanarao Sahukaru @ aitam 57


AITAM Data Structures MCA

It should look like this –

Now, the next node at the left should point to the new node.

This will put the new node in the middle of the two. The new list should look like this –

Insertion in linked list can be done in three different ways. They are explained as follows −

Insertion at Beginning

In this operation, we are adding an element at the beginning of the list.

Algorithm

Jayavardhanarao Sahukaru @ aitam 58


AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void
main(){
int k=0;
insertatbegin(12
);
Jayavardhanarao Sahukaru @ aitam 59
AITAM Data Structures MCA

insertatbegin(22
);
insertatbegin(30
);
insertatbegin(44
);
insertatbegin(50
);
printf("Linked List: ");
// print list
printList();
}

Jayavardhanarao Sahukaru @ aitam 60


AITAM Data Structures MCA

Output:

Insertion at Ending

In this operation, we are adding an element at the ending of the list.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
Jayavardhanarao Sahukaru @ aitam 61
AITAM Data Structures MCA

insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

Jayavardhanarao Sahukaru @ aitam 62


AITAM Data Structures MCA

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void insertatend(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;
struct node *linkedlist = head;

// point it to old first node


while(linkedlist->next !=
NULL) linkedlist = linkedlist-
>next;

//point first to new first


node linkedlist->next =
lk;
}
void
main(){
int k=0;
insertatbegin(12);
insertatend(22);
insertatend(3
0);
insertatend(4
4);
insertatend(5
0);
printf("Linked List: ");

// print list
printList();
}

Output:

Insertion at a Given Position

In this operation, we are adding an element at any position within the list.

Algorithm
Jayavardhanarao Sahukaru @ aitam 63
AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void insertafternode(struct node *list, int data){
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;
lk->next = list-
>next; list->next
Jayavardhanarao Sahukaru @ aitam 64
AITAM Data Structures MCA

= lk;
}
void
main(){
int k=0;
insertatbegin(12);
insertatbegin(22);
insertafternode(head->next,
30); printf("Linked List: ");

Jayavardhanarao Sahukaru @ aitam 65


AITAM Data Structures MCA

// print list
printList();
}

Output:

Linked List - Deletion Operation

Deletion is also a more than one step process. We shall learn with pictorial
representation. First, locate the target node to be removed by using searching
algorithms.

The left (previous) node of the target node now should point to the next node of the target
node –

This will remove the link that was pointing to the target node. Now, using the following
code, we will remove what the target node is pointing at.

We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.

Jayavardhanarao Sahukaru @ aitam 66


AITAM Data Structures MCA

Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and
the new node will point to NULL.

Deletion in linked lists is also performed in three different ways. They are as follows −

Deletion at Beginning

In this deletion operation of the linked, we are deleting an element from the beginning of
the list. For this, we point the head to the second node.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

Jayavardhanarao Sahukaru @ aitam 67


AITAM Data Structures MCA

//start from the beginning


while(p != NULL) {
printf(" %d ",p->data);

Jayavardhanarao Sahukaru @ aitam 68


AITAM Data Structures MCA

p = p->next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void
deleteatbegin(){
head = head-
>next;
}
int main(){
int k=0;
insertatbegin(12
);
insertatbegin(22
);
insertatbegin(30
);
insertatbegin(40
);
insertatbegin(55
);
printf("Linked List: ");

// print list
printList();
deleteatbegin();
printf("\nLinked List after deletion: ");

// print list
printList();
}

Output:
Jayavardhanarao Sahukaru @ aitam 69
AITAM Data Structures MCA

Jayavardhanarao Sahukaru @ aitam 70


AITAM Data Structures MCA

Deletion at Ending

In this deletion operation of the linked, we are deleting an element from the ending of the
list.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

Jayavardhanarao Sahukaru @ aitam 71


AITAM Data Structures MCA

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void deleteatend(){

Jayavardhanarao Sahukaru @ aitam 72


AITAM Data Structures MCA

struct node *linkedlist = head;


while (linkedlist->next->next != NULL)
linkedlist = linkedlist->next;
linkedlist->next = NULL;
}
void
main(){
int k=0;
insertatbegin(12
);
insertatbegin(22
);
insertatbegin(30
);
insertatbegin(40
);
insertatbegin(55
);
printf("Linked List: ");

// print list
printList();
deleteatend();
printf("\nLinked List after deletion: ");

// print list
printList();
}

Output:

Deletion at a Given Position

In this deletion operation of the linked, we are deleting an element at any position of the
list.

Algorithm

Jayavardhanarao Sahukaru @ aitam 73


AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void deletenode(int key){
struct node *temp = head, *prev;
if (temp != NULL CC temp->data
== key) { head = temp->next;
return;
Jayavardhanarao Sahukaru @ aitam 74
AITAM Data Structures MCA

// Find the key to be deleted


while (temp != NULL CC temp->data !=
key) { prev = temp;
temp = temp->next;
}

Jayavardhanarao Sahukaru @ aitam 75


AITAM Data Structures MCA

// If the key is not


present if (temp ==
NULL) return;

// Remove the node


prev->next = temp->next;
}
void
main(){
int k=0;
insertatbegin(12
);
insertatbegin(22
);
insertatbegin(30
);
insertatbegin(40
);
insertatbegin(55
);
printf("Linked List: ");

// print list
printList();
deletenode(30);
printf("\nLinked List after deletion: ");

// print list
printList();
}

Output:

Linked List - Reversal Operation

This operation is a thorough one. We need to make the last node to be pointed by the
head node and reverse the whole linked list.

Jayavardhanarao Sahukaru @ aitam 76


AITAM Data Structures MCA

First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make
it point to its previous node −

Jayavardhanarao Sahukaru @ aitam 77


AITAM Data Structures MCA

We have to make sure that the last node is not the last node. So we'll have some
temp node, which looks like the head node pointing to the last node. Now, we shall make
all left side nodes point to their previous nodes one by one.

Except the node (first node) pointed by the head node, all nodes should point to their
predecessor, making them their new successor. The first node will point to NULL.

We'll make the head node point to the new first node by using the temp node.

Algorithm

Jayavardhanarao Sahukaru @ aitam 78


AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void reverseList(struct node** head){
struct node *prev = NULL, *cur=*head,
*tmp; while(cur!= NULL) {
tmp = cur-
>next; cur-
Jayavardhanarao Sahukaru @ aitam 79
AITAM Data Structures MCA

>next = prev;
prev = cur;
cur = tmp;
}
*head = prev;
}
void
main(){
int k=0;

Jayavardhanarao Sahukaru @ aitam 80


AITAM Data Structures MCA

insertatbegin(12
);
insertatbegin(22
);
insertatbegin(30
);
insertatbegin(40
);
insertatbegin(55
);
printf("Linked List: ");

} // print list
Output: printList();
reverseList(Chead);
printf("\nReversed Linked
List: "); printList();

Linked List - Search Operation

Searching for an element in the list using a key element. This operation is done in the
same way as array search; comparing every element in the list with the key element
given.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
Jayavardhanarao Sahukaru @ aitam 81
AITAM Data Structures MCA

};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList(){

Jayavardhanarao Sahukaru @ aitam 82


AITAM Data Structures MCA

struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");
}

//insertion at the
beginning void
insertatbegin(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
int searchlist(int key){
struct node *temp =
head; while(temp !=
NULL) {
if (temp->data == key)
{ return 1;
}
temp=temp->next;
}
return 0;
}
void
main(){
int k=0;
insertatbegin(12
);
insertatbegin(22
);
insertatbegin(30
);
insertatbegin(40
);
insertatbegin(55
Jayavardhanarao Sahukaru @ aitam 83
AITAM Data Structures MCA

);
printf("Linked List: ");

// print list
printList()
; int ele =
30;
printf("\nElement to be searched is:
%d", ele); k = searchlist(30);
if (k == 1)

Jayavardhanarao Sahukaru @ aitam 84


AITAM Data Structures MCA

printf("\nElement is
found"); else
printf("\nElement is not found in the list");
}
Output:

Linked List - Traversal Operation

The traversal operation walks through all the elements of the list in an order and
displays the elements in that order.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


void printList()
{
struct node *p =
head; printf("\n[");

//start from the beginning


while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
Jayavardhanarao Sahukaru @ aitam 85
AITAM Data Structures MCA

printf("]");
}

//insertion at the beginning


void insertatbegin(int data){

Jayavardhanarao Sahukaru @ aitam 86


AITAM Data Structures MCA

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;

// point it to old first


node lk->next =
head;

//point first to new first node


head = lk;
}
void
main(){
int k=0;
insertatbegin(12
);
insertatbegin(22
);
insertatbegin(30
);
printf("Linked List: ");

// print list
printList()
;
}

Output:

Linked List - Complete implementation

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL;

// display the list


Jayavardhanarao Sahukaru @ aitam 87
AITAM Data Structures MCA

void printList(){
struct node *p =
head; printf("\n[");
//start from the beginning
while(p != NULL) {
printf(" %d ",p-
>data); p = p-
>next;
}
printf("]");

Jayavardhanarao Sahukaru @ aitam 88


AITAM Data Structures MCA

}
//insertion at the
beginning void
insertatbegin(int data){
//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;
// point it to old first
node lk->next =
head;
//point first to new first node
head = lk;
}
void insertatend(int data){

//create a link
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;
struct node *linkedlist = head;

// point it to old first node


while(linkedlist->next !=
NULL) linkedlist = linkedlist-
>next;

//point first to new first


node linkedlist->next =
lk;
}
void insertafternode(struct node *list, int data){
struct node *lk = (struct node*)
malloc(sizeof(struct node)); lk->data = data;
lk->next = list-
>next; list->next
= lk;
}
void
deleteatbegin(){
head = head-
>next;
}
void deleteatend(){
struct node *linkedlist = head;
while (linkedlist->next->next != NULL)
linkedlist = linkedlist->next;
linkedlist->next = NULL;
}
void deletenode(int key){
struct node *temp = head, *prev;
if (temp != NULL CC temp->data
Jayavardhanarao Sahukaru @ aitam 89
AITAM Data Structures MCA

== key) { head = temp->next;


return;
}

// Find the key to be deleted


while (temp != NULL CC temp->data != key) {

Jayavardhanarao Sahukaru @ aitam 90


AITAM Data Structures MCA

prev = temp;
temp = temp->next;
}

// If the key is not


present if (temp ==
NULL) return;

// Remove the node


prev->next = temp->next;
}
int searchlist(int key){
struct node *temp =
head; while(temp !=
NULL) {
if (temp->data == key)
{ return 1;
}
temp=temp->next;
}
return 0;
}
void
main(){
int k=0;
insertatbegin(12
);
insertatbegin(22
);
insertatend(30
);
insertatend(44);
insertatbegin(50);
insertafternode(head->next->next, 33);
printf("Linked List: ");

// print list
printList();
deleteatbegin();
deleteatend();
deletenode(12);
printf("\nLinked List after deletion: ");

// print list
printList();
insertatbegin(4);
insertatbegin(16);
printf("\nUpdated Linked List:
"); printList();
k=
Jayavardhanarao Sahukaru @ aitam 91
AITAM Data Structures MCA

searchlist(16); if
(k == 1)
printf("\nElement is
found"); else
printf("\nElement is not present in the list");
}

Jayavardhanarao Sahukaru @ aitam 92


AITAM Data Structures MCA

Output:

Doubly Linked List


What is Doubly Linked List?

Doubly Linked List is a variation of Linked list in which navigation is possible in both
ways, forward as well as backward easily as compared to Single Linked List. The
following are the important terms to understand the concept of doubly linked list.

 Link − Each link of a linked list can store a data called an element.
 Next − Each link of a linked list contains a link to the next link called Next.
 Prev − Each link of a linked list contains a link to the previous link called Prev.
 Linked List − A Linked List contains the connection link to the first link called
First and to the last link called Last.

Doubly Linked List Representation

As per the above illustration, following are the important points to be considered.

 Doubly Linked List contains a link element called first and last.
 Each link carries a data field(s) and a link field called next.
 Each link is linked with its next link using its next link.
 Each link is linked with its previous link using its previous link.
 The last link carries a link as null to mark the end of the list.

Basic Operations in Doubly Linked List

The following are the basic operations supported by a list.

 Insertion − Adds an element at the beginning of the list.


 Insert Last − Adds an element at the end of the list.
 Insert After − Adds an element after an item of the list.
 Deletion − Deletes an element at the beginning of the list.

Jayavardhanarao Sahukaru @ aitam 93


AITAM Data Structures MCA

 Delete Last − Deletes an element from the end of the list.


 Delete − Deletes an element from the list using the key.
 Display forward − Displays the complete list in a forward manner.
 Display backward − Displays the complete list in a backward manner.

Doubly Linked List - Insertion at the Beginning


In this operation, we create a new node with three compartments, one containing the
data, the others containing the address of its previous and next nodes in the list. This
new node is inserted at the
beginning of the list.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
struct node *prev;
};

//this link always point to first


Link struct node *head =
NULL;

//this link always point to last


Link struct node *last = NULL;
struct node *current = NULL;
Jayavardhanarao Sahukaru @ aitam 94
AITAM Data Structures MCA

//is list empty


bool isEmpty()
{
return head == NULL;
}

//display the doubly linked list

Jayavardhanarao Sahukaru @ aitam 95


AITAM Data Structures MCA

void printList(){
struct node *ptr = head;
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data = data;
if(isEmpty()) {

//make it the last


link last = link;
} else {

//update first prev


link head->prev =
link;
}

//point it to old first


link link->next =
head;

//point first to new first link


head = link;
}
void main(){
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("\nDoubly Linked List:
"); printList();
}

Output:
Doubly Linked List: (6,56) (5,40) (4,1) (3,30) (2,20) (1,10)

Jayavardhanarao Sahukaru @ aitam 96


AITAM Data Structures MCA

Doubly Linked List - Insertion at the End


In this insertion operation, the new input node is added at the end of the doubly linked list;
if the list is not empty. The head will be pointed to the new node, if the list is empty.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
struct node *prev;
};

//this link always point to first


Link struct node *head =
NULL;

//this link always point to last


Link struct node *last = NULL;
struct node *current = NULL;

//is list empty


bool isEmpty()
{
return head == NULL;
}

//display the doubly linked list


Jayavardhanarao Sahukaru @ aitam 97
AITAM Data Structures MCA

void printList(){
struct node *ptr = head;
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}

Jayavardhanarao Sahukaru @ aitam 98


AITAM Data Structures MCA

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data = data;
if(isEmpty()) {

//make it the last


link last = link;
} else {

//update first prev


link head->prev =
link;
}

//point it to old first


link link->next =
head;

//point first to new first link


head = link;
}

//insert link at the last


location void insertLast(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data = data;
if(isEmpty()) {

//make it the last


link last = link;
} else {

//make link a new last


link last->next = link;

//mark old last node as prev of


new link link->prev = last;
}

//point last to new last


Jayavardhanarao Sahukaru @ aitam 99
AITAM Data Structures MCA

node last = link;


}
void main(){

Jayavardhanarao Sahukaru @ aitam 10


0
AITAM Data Structures MCA

insertFirst(1,10)
;
insertFirst(2,20)
;
insertFirst(3,30)
;
insertFirst(4,1
);
} insertLast(5,4
0);
Output: insertLast(6,5
6);
printf("Doubly Linked List: ");
printList();
Doubly Linked List: (4,1) (3,30) (2,20) (1,10) (5,40) (6,56)

Doubly Linked List - Deletion at the Beginning


This deletion operation deletes the existing first nodes in the doubly linked list. The head
is shifted to the next node and the link is removed.

Algorithm

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
struct node *prev;
};

Jayavardhanarao Sahukaru @ aitam 10


1
AITAM Data Structures MCA

//this link always point to first


Link struct node *head =
NULL;

//this link always point to last


Link struct node *last = NULL;
struct node *current = NULL;

//is list empty


bool isEmpty()
{

Jayavardhanarao Sahukaru @ aitam 10


2
AITAM Data Structures MCA

return head == NULL;


}

//display the doubly linked list


void printList(){
struct node *ptr = head;
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data = data;
if(isEmpty()) {

//make it the last


link last = link;
} else {

//update first prev


link head->prev =
link;
}

//point it to old first


link link->next =
head;

//point first to new first link


head = link;
}

//delete first item


struct node* deleteFirst(){

//save reference to first


link struct node *tempLink
= head;

//if only one link


if(head->next ==
NULL) { last = NULL;
} else {
Jayavardhanarao Sahukaru @ aitam 10
3
AITAM Data Structures MCA

head->next->prev = NULL;
}
head = head->next;

Jayavardhanarao Sahukaru @ aitam 10


4
AITAM Data Structures MCA

//return the deleted link


return tempLink;
}
void main(){
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Doubly Linked List: \
n"); printList();
printf("\nList after deleting first record: \n");
deleteFirst();
printList();
}

Output:
Doubly Linked List: (6,56) (5,40) (4,1) (3,30) (2,20) (1,10)
List after deleting first record: (5,40) (4,1) (3,30) (2,20) (1,10)

Doubly Linked List - Complete Implementation

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
struct node *prev;
};

//this link always point to first


Link struct node *head =
NULL;

//this link always point to last


Link struct node *last = NULL;
struct node *current = NULL;

//is list empty


Jayavardhanarao Sahukaru @ aitam 10
5
AITAM Data Structures MCA

bool isEmpty()
{
return head == NULL;
}

//display the list in from first to


last void displayForward(){

Jayavardhanarao Sahukaru @ aitam 10


6
AITAM Data Structures MCA

//start from the beginning


struct node *ptr = head;

//navigate till the end of the list


printf("\n[ ");
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
printf(" ]");
}

//display the list from last to first


void displayBackward(){

//start from the last


struct node *ptr =
last;

//navigate till the start of the list


printf("\n[ ");
while(ptr != NULL) {

//print data
printf("(%d,%d) ",ptr->key,ptr->data);

//move to next item


ptr = ptr ->prev;
printf(" ");
}
printf(" ]");
}

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data = data;
if(isEmpty()) {

//make it the last


link last = link;
} else {

//update first prev


link head->prev =
Jayavardhanarao Sahukaru @ aitam 10
7
AITAM Data Structures MCA

link;
}

Jayavardhanarao Sahukaru @ aitam 10


8
AITAM Data Structures MCA

//point it to old first


link link->next =
head;

//point first to new first link


head = link;
}

//insert link at the last


location void insertLast(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data = data;
if(isEmpty()) {

//make it the last


link last = link;
} else {

//make link a new last


link last->next = link;

//mark old last node as prev of


new link link->prev = last;
}

//point last to new last


node last = link;
}

//delete first item


struct node* deleteFirst(){

//save reference to first


link struct node *tempLink
= head;

//if only one link


if(head->next ==
NULL) { last = NULL;
} else {
head->next->prev = NULL;
}
head = head->next;

//return the deleted link


Jayavardhanarao Sahukaru @ aitam 10
9
AITAM Data Structures MCA

return tempLink;
}

Jayavardhanarao Sahukaru @ aitam 11


0
AITAM Data Structures MCA

//delete link at the last location


struct node* deleteLast(){

//save reference to last


link struct node *tempLink
= last;

//if only one link


if(head->next ==
NULL) { head = NULL;
} else {
last->prev->next = NULL;
}
last = last->prev;

//return the deleted link


return tempLink;
}

//delete a link with given key


struct node* delete(int key){

//start from the first link


struct node* current =
head; struct node*
previous = NULL;

//if list is empty


if(head == NULL) {
return NULL;
}

//navigate through list


while(current->key != key) {

//if it is last node


if(current->next ==
NULL) { return NULL;
} else {

//store reference to current


link previous = current;

//move to next link


current = current-
>next;
}
}

Jayavardhanarao Sahukaru @ aitam 11


1
AITAM Data Structures MCA

//found a match, update the link


if(current == head) {

Jayavardhanarao Sahukaru @ aitam 11


2
AITAM Data Structures MCA

//change first to point to next


link head = head->next;
} else {

//bypass the current link


current->prev->next = current->next;
}
if(current == last) {

//change last to point to prev


link last = current->prev;
} else {
current->next->prev = current->prev;
}
return current;
}
bool insertAfter(int key, int newKey, int data){

//start from the first link


struct node *current =
head;

//if list is empty


if(head == NULL) {
return false;
}

//navigate through list


while(current->key != key) {

//if it is last node


if(current->next ==
NULL) { return false;
} else {

//move to next link


current = current-
>next;
}
}

//create a link
struct node *newLink = (struct node*)
malloc(sizeof(struct node)); newLink->key = key;
newLink->data =
data; if(current ==
last) {
newLink->next =
NULL; last = newLink;
Jayavardhanarao Sahukaru @ aitam 11
3
AITAM Data Structures MCA

} else {
newLink->next = current->next;

Jayavardhanarao Sahukaru @ aitam 11


4
AITAM Data Structures MCA

current->next->prev = newLink;
}
newLink->prev =
current; current->next
= newLink; return
true;
}
int main(){
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("\nList (First to Last): ");
displayForward();
printf("\n");
printf("\nList (Last to first): ");
displayBackward();
printf("\nList , after deleting first record: ");
deleteFirst();
displayForward();
printf("\nList , after deleting last record: ");
deleteLast();
displayForward();
printf("\nList , insert after key(4) : ");
insertAfter(4,7, 13);
displayForward();
printf("\nList , after delete key(4) : ");
delete(4);
displayForward();
}

Output:

List (First to Last):


[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]

List (Last to first):


[ (1,10) (2,20) (3,30) (4,1) (5,40) (6,56) ]
List , after deleting first record:
[ (5,40) (4,1) (3,30) (2,20) (1,10) ]
List , after deleting last
record: [ (5,40) (4,1)
(3,30) (2,20) ]
List , insert after key(4) :
[ (5,40) (4,1) (4,13) (3,30) (2,20) ]
List , after delete key(4) :
[ (5,40) (4,13) (3,30) (2,20) ]

Jayavardhanarao Sahukaru @ aitam 11


5
AITAM Data Structures MCA

Circular Linked List

What is Circular Linked List?

Circular Linked List is a variation of Linked list in which the first element points to the last
element and the last element points to the first element. Both Singly Linked List and
Doubly Linked List can be made into a circular linked list.

Singly Linked List as Circular


In singly linked list, the next pointer of the last node points to the first node.

Doubly Linked List as Circular

In doubly linked list, the next pointer of the last node points to the first node and the
previous pointer of the first node points to the last node making the circular in both
directions.

As per the above illustration, the following are the important points to be considered.
 The last link's next points to the first link of the list in both cases of singly as
well as doubly linked list.
 The first link's previous points to the last of the list in case of doubly linked list.

Basic Operations in Circular Linked List


The following are the important operations supported by a circular list.
 insert − Inserts an element at the start of the list.
 delete − Deletes an element from the start of the list.
 display − Displays the list.

Circular Linked List - Insertion Operation


The insertion operation of a circular linked list only inserts the element at the start of the list.
This differs from the usual singly and doubly linked lists as there is no particular starting
and ending points in this list. The insertion is done either at the start or after a
particular node (or a given position) in the list.

Algorithm

Jayavardhanarao Sahukaru @ aitam 11


6
AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL; bool
isEmpty(){
return head == NULL;
}

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data =
data; if
(isEmpty()) {
head = link;
head->next = head;
} else {

//point it to old first


node link->next =
head;

//point first to new first


node head = link;
}
}

//display the list


void printList(){
struct node *ptr = head;
Jayavardhanarao Sahukaru @ aitam 11
7
AITAM Data Structures MCA

printf("\n[ ");

//start from the beginning


if(head != NULL) {
while(ptr->next != ptr) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}

Jayavardhanarao Sahukaru @ aitam 11


8
AITAM Data Structures MCA

printf(" ]");
}
void main(){
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Circular Linked List: ");

//print list
printList();
}

Output:
Circular Linked List:
[ (6,56) (5,40) (4,1) (3,30) (2,20) ]

Circular Linked List - Deletion Operation


The Deletion operation in a Circular linked list removes a certain node from the list. The
deletion operation in this type of lists can be done at the beginning, or a given position,
or at the ending.

Algorithm

Jayavardhanarao Sahukaru @ aitam 11


9
AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL; bool
isEmpty(){
return head == NULL;
}

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data =
data; if
(isEmpty()) {
head = link;
head->next = head;
} else {

//point it to old first


node link->next =
head;

//point first to new first


node head = link;
}
}

//delete first item


struct node * deleteFirst(){

Jayavardhanarao Sahukaru @ aitam 12


0
AITAM Data Structures MCA

//save reference to first


link struct node *tempLink
= head; if(head->next
== head) {
head = NULL;
return
tempLink;
}

//mark next to first link as


first head = head->next;

Jayavardhanarao Sahukaru @ aitam 12


1
AITAM Data Structures MCA

//return the deleted link


return tempLink;
}

//display the list


void printList(){
struct node *ptr = head;

//start from the beginning


if(head != NULL) {
while(ptr->next != ptr) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}
}
void main(){
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Circular Linked List: ");

//print list
printList();
deleteFirst();
printf("\nList after deleting the first item: ");
printList();
}

Output:
Circular Linked List: (6,56) (5,40) (4,1) (3,30) (2,20)
List after deleting the first item: (5,40) (4,1) (3,30) (2,20)

Circular Linked List - Displaying the List


The Display List operation visits every node in the list and prints them all in the output.

Algorithm

Jayavardhanarao Sahukaru @ aitam 12


2
AITAM Data Structures MCA

Example

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL; bool
isEmpty(){
return head == NULL;
}

//insert link at the first


location void insertFirst(int
key, int data){

//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data =
data; if
(isEmpty()) {
head = link;
head->next = head;
} else {

//point it to old first


node link->next =
head;

//point first to new first


node head = link;
}
}

//display the list


void printList(){
struct node *ptr = head;
Jayavardhanarao Sahukaru @ aitam 12
3
AITAM Data Structures MCA

printf("\n[ ");

//start from the beginning


if(head != NULL) {
while(ptr->next != ptr) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}

Jayavardhanarao Sahukaru @ aitam 12


4
AITAM Data Structures MCA

printf(" ]");
}
void main(){
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Circular Linked List: ");

//print list
printList();
}

Output:
Circular Linked List:
[ (6,56) (5,40) (4,1) (3,30) (2,20) ]

Circular Linked List - Complete Implementation

#include
<stdio.h>
#include
<string.h>
#include
<stdlib.h>
#include
<stdbool.h>
struct node {
int
data;
int
key;
struct node *next;
};
struct node *head =
NULL; struct node
*current = NULL; bool
isEmpty(){
return head == NULL;
}
int length(){
int length = 0;
//if list is empty
if(head == NULL) {
return 0;
}
current = head->next;
Jayavardhanarao Sahukaru @ aitam 12
5
AITAM Data Structures MCA

while(current != head) {
length++;
current = current->next;
}
return length;
}

Jayavardhanarao Sahukaru @ aitam 12


6
AITAM Data Structures MCA

//insert link at the first


location void insertFirst(int
key, int data){
//create a link
struct node *link = (struct node*)
malloc(sizeof(struct node)); link->key = key;
link->data =
data; if
(isEmpty()) {
head = link;
head->next = head;
} else {
//point it to old first
node link->next =
head;

//point first to new first


node head = link;
}
}
//delete first item
struct node * deleteFirst(){

//save reference to first


link struct node *tempLink
= head; if(head->next
== head) {
head = NULL;
return
tempLink;
}
//mark next to first link as
first head = head->next;

//return the deleted link


return tempLink;
}
//display the list
void printList(){
struct node *ptr = head;
printf("\n[ ");
//start from the beginning
if(head != NULL) {
while(ptr->next != ptr) {
printf("(%d,%d) ",ptr->key,ptr-
>data); ptr = ptr->next;
}
}
printf(" ]");
}
Jayavardhanarao Sahukaru @ aitam 12
7
AITAM Data Structures MCA

int main(){
insertFirst(1,10
);
insertFirst(2,20
);
insertFirst(3,30
);

Jayavardhanarao Sahukaru @ aitam 12


8
AITAM Data Structures MCA

insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Original List: ");
//print list
printList();
while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
printf("\nList after deleting all items: ");
printList();
}

Output:

Original List:
[ (6,56) (5,40) (4,1) (3,30) (2,20) ]
Deleted value:(6,56)
Deleted value:(5,40)
Deleted value:(4,1)
Deleted value:(3,30)
Deleted value:(2,20)
Deleted value:(1,10)
List after deleting all
items: [ ]

Jayavardhanarao Sahukaru @ aitam 12


9

You might also like