0% found this document useful (0 votes)
29 views99 pages

Arrays and Linked Lists Overview

The document covers the fundamentals of arrays and linked lists, detailing their properties, representation, operations, and complexities. It explains how arrays are collections of similar data types stored in contiguous memory locations, with various operations such as insertion, deletion, searching, and updating. Additionally, it discusses the advantages and disadvantages of arrays, as well as their applications in programming.
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)
29 views99 pages

Arrays and Linked Lists Overview

The document covers the fundamentals of arrays and linked lists, detailing their properties, representation, operations, and complexities. It explains how arrays are collections of similar data types stored in contiguous memory locations, with various operations such as insertion, deletion, searching, and updating. Additionally, it discusses the advantages and disadvantages of arrays, as well as their applications in programming.
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

UNIT II

Arrays & Linked Lists

SYLLABUS:

Arrays & Linked Lists: Arrays, Single and Multidimensional Arrays, address calculation,
application of arrays, linked list: Representation and implementation of Singly Linked Lists, Header
List, Traversing and Searching of Linked List, Overflow and Underflow, Insertion and deletion to and
from Linked Lists, doubly linked list.

Array in Data Structure


Arrays are defined as the collection of similar types of data items stored at contiguous
memory locations. It is one of the simplest data structures where each data element can be
randomly accessed by using its index number.

In C programming, they are the derived data types that can store the primitive type of data
such as int, char, double, float, etc. For example, if we want to store the marks of a student in
6 subjects, then we don't need to define a different variable for the marks in different
subjects. Instead, we can define an array that can store the marks in each subject at the
contiguous memory locations.

Properties of array

There are some of the properties of an array that are listed as follows -

o Each element in an array is of the same data type and carries the same size that is 4
bytes.
o Elements in the array are stored at contiguous memory locations from which the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data
element.

Representation of an array

We can represent an array in various ways in different programming languages. As an


illustration, let's see the declaration of array in C language -

55.2M
998
Prime Ministers of India | List of Prime Minister of India (1947-2020)
As per the above illustration, there are some of the following important points -

o Index starts with 0.


o The array's length is 10, which means we can store 10 elements.
o Each element in the array can be accessed via its index.

Why are arrays required?

Arrays are useful because -

o Sorting and searching a value in an array is easier.


o Arrays are best to process multiple values quickly and easily.
o Arrays are good for storing multiple values in a single variable - In computer
programming, most cases require storing a large number of data of a similar type. To
store such an amount of data, we need to define a large number of variables. It would
be very difficult to remember the names of all the variables while writing the
programs. Instead of naming all the variables with a different name, it is better to
define an array and store all the elements into it.

Memory allocation of an array

As stated above, all the data elements of an array are stored at contiguous locations in the
main memory. The name of the array represents the base address or the address of the first
element in the main memory. Each element of the array is represented by proper indexing.

We can define the indexing of an array in the below ways -

1. 0 (zero-based indexing): The first element of the array will be arr[0].


2. 1 (one-based indexing): The first element of the array will be arr[1].
3. n (n - based indexing): The first element of the array can reside at any random index
number.

In the above image, we have shown the memory allocation of an array arr of size 5. The array
follows a 0-based indexing approach. The base address of the array is 100 bytes. It is the
address of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each element will
take 4 bytes in the memory.
How to access an element from the array?

We required the information given below to access any random element from the array -

o Base Address of the array.


o Size of an element in bytes.
o Type of indexing, array follows.

The formula to calculate the address to access an array element -

1. Byte address of element A[i] = base address + size * ( i - first index)

Here, size represents the memory taken by the primitive data types. As an instance, int takes
2 bytes, float takes 4 bytes of memory space in C programming.

We can understand it with the help of an example -

Suppose an array, A[-10 ..... +2 ] having Base address (BA) = 999 and size of an element = 2
bytes, find the location of A[-1].

L(A[-1]) = 999 + 2 x [(-1) - (-10)]

= 999 + 18

= 1017

Basic operations
Now, let's discuss the basic operations supported in the array -

o Traversal - This operation is used to print the elements of the array.


o Insertion - It is used to add an element at a particular index.
o Deletion - It is used to delete an element from a particular index.
o Search - It is used to search an element using the given index or by the value.
o Update - It updates an element at a particular index.

Traversal operation

This operation is performed to traverse through the array elements. It prints all array
elements one after another. We can understand it with the below program -

1. #include <stdio.h>
2. void main() {
3. int Arr[5] = {18, 30, 15, 70, 12};
4. int i;
5. printf("Elements of the array are:\n");
6. for(i = 0; i<5; i++) {
7. printf("Arr[%d] = %d, ", i, Arr[i]);
8. }
9. }

Output

Insertion operation

This operation is performed to insert one or more elements into the array. As per the
requirements, an element can be added at the beginning, end, or at any index of the array.
Now, let's see the implementation of inserting an element into the array.

1. #include <stdio.h>
2. int main()
3. {
4. int arr[20] = { 18, 30, 15, 70, 12 };
5. int i, x, pos, n = 5;
6. printf("Array elements before insertion\n");
7. for (i = 0; i < n; i++)
8. printf("%d ", arr[i]);
9. printf("\n");
10.
11. x = 50; // element to be inserted
12. pos = 4;
13. n++;
14.
15. for (i = n-1; i >= pos; i--)
16. arr[i] = arr[i - 1];
17. arr[pos - 1] = x;
18. printf("Array elements after insertion\n");
19. for (i = 0; i < n; i++)
20. printf("%d ", arr[i]);
21. printf("\n");
22. return 0;
23. }

Output

Deletion operation

As the name implies, this operation removes an element from the array and then reorganizes
all of the array elements.
1. #include <stdio.h>
2.
3. void main() {
4. int arr[] = {18, 30, 15, 70, 12};
5. int k = 30, n = 5;
6. int i, j;
7.
8. printf("Given array elements are :\n");
9.
10. for(i = 0; i<n; i++) {
11. printf("arr[%d] = %d, ", i, arr[i]);
12. }
13.
14. j = k;
15.
16. while( j < n) {
17. arr[j-1] = arr[j];
18. j = j + 1;
19. }
20.
21. n = n -1;
22.
23. printf("\nElements of array after deletion:\n");
24.
25. for(i = 0; i<n; i++) {
26. printf("arr[%d] = %d, ", i, arr[i]);
27. }
28. }

Output

Search operation

This operation is performed to search an element in the array based on the value or index.

1. #include <stdio.h>
2.
3. void main() {
4. int arr[5] = {18, 30, 15, 70, 12};
5. int item = 70, i, j=0 ;
6.
7. printf("Given array elements are :\n");
8.
9. for(i = 0; i<5; i++) {
10. printf("arr[%d] = %d, ", i, arr[i]);
11. }
12. printf("\nElement to be searched = %d", item);
13. while( j < 5){
14. if( arr[j] == item ) {
15. break;
16. }
17.
18. j = j + 1;
19. }
20.
21. printf("\nElement %d is found at %d position", item, j+1);
22. }

Output

Update operation

This operation is performed to update an existing array element located at the given index.

1. #include <stdio.h>
2.
3. void main() {
4. int arr[5] = {18, 30, 15, 70, 12};
5. int item = 50, i, pos = 3;
6.
7. printf("Given array elements are :\n");
8.
9. for(i = 0; i<5; i++) {
10. printf("arr[%d] = %d, ", i, arr[i]);
11. }
12.
13. arr[pos-1] = item;
14. printf("\nArray elements after updation :\n");
15.
16. for(i = 0; i<5; i++) {
17. printf("arr[%d] = %d, ", i, arr[i]);
18. }
19. }
Output

Complexity of Array operations


Time and space complexity of various array operations are described in the following table.

Time Complexity

Operation Average Case Worst Case

Access O(1) O(1)

Search O(n) O(n)

Insertion O(n) O(n)

Deletion O(n) O(n)

Space Complexity

In array, space complexity for worst case is O(n).

Advantages of Array
o Array provides the single name for the group of variables of the same type. Therefore,
it is easy to remember the name of all the elements of an array.
o Traversing an array is a very simple process; we just need to increment the base
address of the array in order to visit each element one by one.
o Any element in the array can be directly accessed by using the index.

Disadvantages of Array
o Array is homogenous. It means that the elements with similar data type can be stored
in it.
o In array, there is static memory allocation that is size of an array cannot be altered.
o There will be wastage of memory if we store less number of elements than the
declared size.
Array is a type of linear data structure that is defined as a collection of elements with same or different data
types. They exist in both single dimension and multiple dimensions. These data structures come into
picture when there is a necessity to store multiple elements of similar nature together at one place.

The difference between an array index and a memory address is that the array index acts like a key value
to label the elements in the array. However, a memory address is the starting address of free memory
available.
Following are the important terms to understand the concept of Array.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is used to identify the
element.
Syntax
Creating an array in C and C++ programming languages −
data_type array_name[array_size] = {elements separated using commas}
or,
data_type array_name[array_size];
Creating an array in JAVA programming language −
data_type[] array_name = {elements separated by commas}
or,
data_type array_name = new data_type[array_size];

Need for Arrays


Arrays are used as solutions to many problems from the small sorting problems to more complex problems
like travelling salesperson problem. There are many data structures other than arrays that provide efficient
time and space complexity for these problems, so what makes using arrays better? The answer lies in the
random access lookup time.
Arrays provide O(1) random access lookup time. That means, accessing the 1st index of the array and the
1000th index of the array will both take the same time. This is due to the fact that array comes with a pointer
and an offset value. The pointer points to the right location of the memory and the offset value shows how
far to look in the said memory.
array_name[index]
| |
Pointer Offset
Therefore, in an array with 6 elements, to access the 1st element, array is pointed towards the 0th index.
Similarly, to access the 6th element, array is pointed towards the 5th index.

Array Representation
Arrays are represented as a collection of buckets where each bucket stores one element. These buckets
are indexed from ‘0’ to ‘n-1’, where n is the size of that particular array. For example, an array with size 10
will have buckets indexed from 0 to 9.
This indexing will be similar for the multidimensional arrays as well. If it is a 2-dimensional array, it will have
sub-buckets in each bucket. Then it will be indexed as array_name[m][n], where m and n are the sizes of
each level in the array.

As per the above illustration, following are the important points to be considered.
 Index starts with 0.
 Array length is 9 which means it can store 9 elements.
 Each element can be accessed via its index. For example, we can fetch an element at index 6 as 23.

Basic Operations in the Arrays


The basic operations in the Arrays are insertion, deletion, searching, display, traverse, and update. These
operations are usually performed to either modify the data in the array or to report the status of the array.
Following are the basic operations supported by an array.
 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.
 Display − Displays the contents of the array.
In C, when an array is initialized with size, then it assigns defaults values to its elements in following order.

Data Type Default Value

bool false

char 0
int 0

float 0.0

double 0.0f

void

wchar_t 0

Insertion Operation
In the insertion operation, we are adding one or more elements to the array. Based on the requirement, a
new element can be added at the beginning, end, or any given index of array. This is done using input
statements of the programming languages.

Algorithm
Following is an algorithm to insert elements into a Linear Array until we reach the end of the array −
1. Start
2. Create an Array of a desired datatype and size.
3. Initialize a variable ‘i’ as 0.
4. Enter the element at ith index of the array.
5. Increment i by 1.
6. Repeat Steps 4 & 5 until the end of the array.
7. Stop
Here, we see a practical implementation of insertion operation, where we add data at the end of the array −

Example
CC++Java
#include <stdio.h>

int main(){

int LA[3], i;

printf("Array Before Insertion:\n");

for(i = 0; i < 3; i++)

printf("LA[%d] = %d \n", i, LA[i]);

printf("Inserting Elements.. ");

printf("The array elements after insertion :\n"); // prints array values

for(i = 0; i < 3; i++) {

LA[i] = i + 2;

printf("LA[%d] = %d \n", i, LA[i]);

return 0;

Output
Array Before Insertion:
LA[0] = 587297216
LA[1] = 32767 LA[2] = 0
Inserting Elements.. The array elements after insertion :
LA[0] = 2
LA[1] = 3
LA[2] = 4
For other variations of array insertion operation, click here.
Deletion Operation
In this array operation, we delete an element from the particular index of an array. This deletion operation
takes place as we assign the value in the consequent index to the current index.

Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to delete an element available at the Kth position of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#include <stdio.h>

void main(){

int LA[] = {1,3,5};

int n = 3;

int i;

printf("The original array elements are :\n");

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

printf("LA[%d] = %d \n", i, LA[i]);

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

LA[i] = LA[i+1];

n = n – 1;

printf("The array elements after deletion :\n");

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

printf("LA[%d] = %d \n", i, LA[i]);

Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
The array elements after deletion :
LA[0] = 1
LA[1] = 5

Search Operation
Searching an element in the array using a key; The key element sequentially compares every value in the
array to check if the key is present in the array or not.

Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to find an element with a value of ITEM using sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#include <stdio.h>

void main(){

int LA[] = {1,3,5,7,8};

int item = 5, n = 5;

int i = 0, j = 0;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

for(i = 0; i<n; i++) {

if( LA[i] == item ) {

printf("Found element %d at position %d\n", item, i+1);

Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Found element 5 at position 3

Traversal Operation
This operation traverses through all the elements of an array. We use loop statements to carry this out.

Algorithm
Following is the algorithm to traverse through all the elements present in a Linear Array −
1 Start
2. Initialize an Array of certain size and datatype.
3. Initialize another variable ‘i’ with 0.
4. Print the ith value in the array and increment i.
5. Repeat Step 4 until the end of the array is reached.
6. End
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#include <stdio.h>

int main(){

int LA[] = {1,3,5,7,8};

int item = 10, k = 3, n = 5;

int i = 0, j = n;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8

Update Operation
Update operation refers to updating an existing element from the array at a given index.

Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the
algorithm to update an element available at the Kth position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#include <stdio.h>

void main(){

int LA[] = {1,3,5,7,8};

int k = 3, n = 5, item = 10;

int i, j;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

LA[k-1] = item;
printf("The array elements after updation :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5 LA[3] = 7
LA[4] = 8
The array elements after updation :
LA[0] = 1
LA[1] = 3
LA[2] = 10
LA[3] = 7
LA[4] = 8

Display Operation
This operation displays all the elements in the entire array using a print statement.

Algorithm
1. Start
2. Print all the elements in the Array
3. Stop
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#include <stdio.h>

int main(){

int LA[] = {1,3,5,7,8};

int n = 5;

int i;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Types of Arrays:
There are two types of arrays:

 One-Dimensional Arrays
 Multi-Dimensional Arrays

One -Dimensional Arrays


A one-dimensional array is a kind of linear array. It involves single sub-scripting. The [] (brackets) is used for the
subscript of the array and to declare and access the elements from the array.
Syntax: DataType ArrayName [size];
For example: int a[10];

Multi-Dimensional Arrays
In multi-dimensional arrays, we have two categories:

 Two-Dimensional Arrays
 Three-Dimensional Arrays

1. Two-Dimensional Arrays

An array involving two subscripts [] [] is known as a two-dimensional array. They are also known as the array of the
array. Two-dimensional arrays are divided into rows and columns and are able to handle the data of the table.

Syntax: DataType ArrayName[row_size][column_size];


For Example: int arr[5][5];
2. Three-Dimensional Arrays
When we require to create two or more tables of the elements to declare the array elements, then in such a situation we
use three-dimensional arrays.
Syntax: DataType ArrayName[size1][size2][size3];
For Example: int a[5][5][5];

Difference Between One-Dimensional and Two-Dimensional Array


Parameters One-Dimensional Array Two-Dimensional Array

Basics A one-dimensional array stores a A two-dimensional array stores an array of


single list of various elements various arrays, or a list of various lists, or
having a similar data type. an array of various one-dimensional arrays.

Representation It represents multiple data items It represents multiple data items in the form
in the form of a list. of a table that contains columns and rows.

Dimensions It has only one dimension. It has a total of two dimensions.

Parameters of One can easily receive it in a The parameters that receive it must define
Receiving pointer, an unsized array, or a an array’s rightmost dimension.
sized array.

Total Size (in terms Total number of Bytes = The size Total number of Bytes = The size of array
of Bytes) of array x the size of array visible or datatype x the size of second
variable or datatype. index x the size of the first index.

Advantages of Array

 It is a better version of storing the data of the same size and same type.
 It enables us to collect the number of elements in it.
 Arrays have a safer cache positioning that improves performance.
 Arrays can represent multiple data items of the same type using a single name.

Disadvantages Of Array:

 In an array, it is essential to identify the number of elements to be stored.


 It is a static structure. It means that in an array, the memory size is fixed.
 When it comes to insertion and deletion, it is a bit difficult because the elements are stored sequentially and
the shifting operation is expensive.

2D Array
2D array can be defined as an array of arrays. The 2D array is organized as matrices which
can be represented as the collection of rows and columns.

However, 2D arrays are created to implement a relational database look alike data structure.
It provides ease of holding bulk of data at once which can be passed to any number of
functions wherever required.

How to declare 2D Array


The syntax of declaring two dimensional array is very much similar to that of a one
dimensional array, given as follows.
1. int arr[max_rows][max_columns];

however, It produces the data structure which looks like following.

Above image shows the two dimensional array, the elements are organized in the form of
rows and columns. First element of the first row is represented by a[0][0] where the number
shown in the first index is the number of that row while the number shown in the second
index is the number of the column.

How do we access data in a 2D array


Due to the fact that the elements of 2D arrays can be random accessed. Similar to one
dimensional arrays, we can access the individual cells in a 2D array by using the indices of
the cells. There are two indices attached to a particular cell, one is its row number while the
other is its column number.

However, we can store the value stored in any particular cell of a 2D array to some variable x
by using the following syntax.

1. int x = a[i][j];

where i and j is the row and column number of the cell respectively.

We can assign each cell of a 2D array to 0 by using the following code:

1. for ( int i=0; i<n ;i++)


2. {
3. for (int j=0; j<n; j++)
4. {
5. a[i][j] = 0;
6. }
7. }

Initializing 2D Arrays
We know that, when we declare and initialize one dimensional array in C programming
simultaneously, we don't need to specify the size of the array. However this will not work with
2D arrays. We will have to define at least the second dimension of the array.

The syntax to declare and initialize the 2D array is given as follows.

1. int arr[2][2] = {0,1,2,3};

The number of elements that can be present in a 2D array will always be equal to ( number
of rows * number of columns).

Example : Storing User's data into a 2D array and printing it.

C Example :

1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }
Mapping 2D array to 1D array
When it comes to map a 2 dimensional array, most of us might think that why this mapping is
required. However, 2 D arrays exists from the user point of view. 2D arrays are created to
implement a relational database table lookalike data structure, in computer memory, the
storage technique for 2D array is similar to that of an one dimensional array.

The size of a two dimensional array is equal to the multiplication of number of rows and the
number of columns present in the array. We do need to map two dimensional array to the one
dimensional array in order to store them in the memory.

A 3 X 3 two dimensional array is shown in the following image. However, this array needs to
be mapped to a one dimensional array in order to store it into the memory.

There are two main techniques of storing 2D array elements into memory

1. Row Major ordering

In row major ordering, all the rows of the 2D array are stored into the memory contiguously.
Considering the array shown in the above image, its memory allocation according to row
major order is shown as follows.

first, the 1st row of the array is stored into the memory completely, then the 2 nd row of the
array is stored into the memory completely and so on till the last row.
2. Column Major ordering

According to the column major ordering, all the columns of the 2D array are stored into the
memory contiguously. The memory allocation of the array which is shown in in the above
image is given as follows.

first, the 1st column of the array is stored into the memory completely, then the 2 nd row of the
array is stored into the memory completely and so on till the last column of the array.

Calculating the Address of the random element of a 2D array


Due to the fact that, there are two different techniques of storing the two dimensional array
into the memory, there are two different formulas to calculate the address of a random
element of the 2D array.

By Row Major Order


If array is declared by a[m][n] where m is the number of rows while n is the number of
columns, then address of an element a[i][j] of the array stored in row major order is
calculated as,

1. Address(a[i][j]) = B. A. + (i * n + j) * size

where, B. A. is the base address or the address of the first element of the array a[0][0] .

Example :

1. a[10...30, 55...75], base address of the array (BA) = 0, size of an element = 4 bytes .
2. Find the location of a[15][68].
3.
4. Address(a[15][68]) = 0 +
5. ((15 - 10) x (68 - 55 + 1) + (68 - 55)) x 4
6.
7. = (5 x 14 + 13) x 4
8. = 83 x 4
9. = 332 answer

By Column major order

If array is declared by a[m][n] where m is the number of rows while n is the number of
columns, then address of an element a[i][j] of the array stored in row major order is
calculated as,

1. Address(a[i][j]) = ((j*m)+i)*Size + BA

where BA is the base address of the array.

Example:

1. A [-5 ... +20][20 ... 70], BA = 1020, Size of element = 8 bytes. Find the location of a[0][30].
2.
3. Address [A[0][30]) = ((30-20) x 24 + 5) x 8 + 1020 = 245 x 8 + 1020 = 2980 bytes
Applications of Array Data Structure:

Below are some applications of arrays.

Storing and accessing data: Arrays are used to store and retrieve data in a specific order. For
example, an array can be used to store the scores of a group of students, or the temperatures
recorded by a weather station.

Sorting: Arrays can be used to sort data in ascending or descending order. Sorting algorithms such as
bubble sort, merge sort, and quicksort rely heavily on arrays.

Searching: Arrays can be searched for specific elements using algorithms such as linear search and
binary search.

Matrices: Arrays are used to represent matrices in mathematical computations such as matrix
multiplication, linear algebra, and image processing.

Stacks and queues: Arrays are used as the underlying data structure for implementing stacks and
queues, which are commonly used in algorithms and data structures.

Graphs: Arrays can be used to represent graphs in computer science. Each element in the array
represents a node in the graph, and the relationships between the nodes are represented by the
values stored in the array.

Dynamic programming: Dynamic programming algorithms often use arrays to store intermediate
results of subproblems in order to solve a larger problem.

Real-Time Applications of Array:

Below are some real-time applications of arrays.

Signal Processing: Arrays are used in signal processing to represent a set of samples that are
collected over time. This can be used in applications such as speech recognition, image processing,
and radar systems.

Multimedia Applications: Arrays are used in multimedia applications such as video and audio
processing, where they are used to store the pixel or audio samples. For example, an array can be
used to store the RGB values of an image.

Data Mining: Arrays are used in data mining applications to represent large datasets. This allows for
efficient data access and processing, which is important in real-time applications.

Robotics: Arrays are used in robotics to represent the position and orientation of objects in 3D
space. This can be used in applications such as motion planning and object recognition.

Real-time Monitoring and Control Systems: Arrays are used in real-time monitoring and control
systems to store sensor data and control signals. This allows for real-time processing and decision-
making, which is important in applications such as industrial automation and aerospace systems.

Financial Analysis: Arrays are used in financial analysis to store historical stock prices and other
financial data. This allows for efficient data access and analysis, which is important in real-time
trading systems.
Scientific Computing: Arrays are used in scientific computing to represent numerical data, such as
measurements from experiments and simulations. This allows for efficient data processing and
visualization, which is important in real-time scientific analysis and experimentation.

Advantages of array data structure:

Efficient access to elements: Arrays provide direct and efficient access to any element in the
collection. Accessing an element in an array is an O(1) operation, meaning that the time required to
access an element is constant and does not depend on the size of the array.

Fast data retrieval: Arrays allow for fast data retrieval because the data is stored in contiguous
memory locations. This means that the data can be accessed quickly and efficiently without the need
for complex data structures or algorithms.

Memory efficiency: Arrays are a memory-efficient way of storing data. Because the elements of an
array are stored in contiguous memory locations, the size of the array is known at compile time. This
means that memory can be allocated for the entire array in one block, reducing memory
fragmentation.

Versatility: Arrays can be used to store a wide range of data types, including integers, floating-point
numbers, characters, and even complex data structures such as objects and pointers.

Easy to implement: Arrays are easy to implement and understand, making them an ideal choice for
beginners learning computer programming.

Compatibility with hardware: The array data structure is compatible with most hardware
architectures, making it a versatile tool for programming in a wide range of environments.

Disadvantages of array data structure:

Fixed size: Arrays have a fixed size that is determined at the time of creation. This means that if the
size of the array needs to be increased, a new array must be created and the data must be copied
from the old array to the new array, which can be time-consuming and memory-intensive.

Memory allocation issues: Allocating a large array can be problematic, particularly in systems with
limited memory. If the size of the array is too large, the system may run out of memory, which can
cause the program to crash.

Insertion and deletion issues: Inserting or deleting an element from an array can be inefficient and
time-consuming because all the elements after the insertion or deletion point must be shifted to
accommodate the change.

Wasted space: If an array is not fully populated, there can be wasted space in the memory allocated
for the array. This can be a concern if memory is limited.

Limited data type support: Arrays have limited support for complex data types such as objects and
structures, as the elements of an array must all be of the same data type.

Lack of flexibility: The fixed size and limited support for complex data types can make arrays
inflexible compared to other data structures such as linked lists and trees.

Advantages of Structure over Array:

The structure can store different types of data whereas an array can only store similar data types.
Structure does not have limited size like an array.

Structure elements may or may not be stored in contiguous locations but array elements are stored
in contiguous locations.

In structures, object instantiation is possible whereas in arrays objects are not possible.
Linked list
A linked list is a collection of “nodes” connected together via links. These nodes consist of the data to be
stored and a pointer to the address of the next node within the linked list. In the case of arrays, the size is
limited to the definition, but in linked lists, there is no defined size. Any amount of data can be stored in it
and can be deleted from it.
There are three types of linked lists −
 Singly Linked List − The nodes only point to the address of the next node in the list.
 Doubly Linked List − The nodes point to the addresses of both previous and next nodes.
 Circular Linked List − The last node in the list will point to the first node in the list. It can either be
singly linked or doubly linked.

Linked List Representation


Linked list can be visualized as a chain of nodes, where every node points to the next node.

As per the above illustration, following are the important points to be considered.
 Linked List contains a link element called first (head).
 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.
 Last link carries a link as null to mark the end of the list.

Types of Linked List


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 list is traversed twice as the nodes in the
list are connected to each other from both sides.

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 the Linked Lists


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.

Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with diagrams here.
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
[Link] to C −
[Link] −> RightNode;
It should look like this −

Now, the next node at the left should point to the new node.
[Link] −> NewNode;

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
1. START
2. Create a node to store the data
3. Check if the list is empty
4. If the list is empty, add the data to the node and assign the head pointer to it.
5 If the list is not empty, add the data to a node and link to the current head. Assign the head to
the newly added node.
6. END
Example
Following are the implementations of this operation in various programming languages −
CC++JavaPython
#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);

insertatbegin(22);

insertatbegin(30);

insertatbegin(44);

insertatbegin(50);

printf("Linked List: ");


// print list

printList();

Output
Linked List:
[ 50 44 30 22 12 ]
Insertion at Ending
In this operation, we are adding an element at the ending of the list.

Algorithm
1. START
2. Create a new node and assign the data
3. Find the last node
4. Point the last node to new node
5. END
Example
Following are the implementations of this operation in various programming languages −
CC++JavaPython
#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 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(30);

insertatend(44);

insertatend(50);

printf("Linked List: ");

// print list

printList();
}

Output
Linked List:
[ 12 22 30 44 50 ]
Insertion at a Given Position
In this operation, we are adding an element at any position within the list.

Algorithm
1. START
2. Create a new node and assign data to it
3. Iterate until the node at position is found
4. Point first to new first node
5. END
Example
Following are the implementations of this operation in various programming languages −
CC++JavaPython
#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 = lk;

void main(){

int k=0;

insertatbegin(12);

insertatbegin(22);

insertafternode(head->next, 30);

printf("Linked List: ");

// print list

printList();

Output
Linked List:
[ 22 12 30 ]

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 −
[Link] −> [Link];

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.
[Link] −> NULL;

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.

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
1. START
2. Assign the head pointer to the next node in the list
3. END
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#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 deleteatbegin(){

head = head->next;

void 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
Linked List:
[ 55 40 30 22 12 ]
Linked List after deletion:
[ 40 30 22 12 ]
Deletion at Ending
In this deletion operation of the linked, we are deleting an element from the ending of the list.

Algorithm
1. START
2. Iterate until you find the second last element in the list.
3. Assign NULL to the second last element in the list.
4. END
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#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 deleteatend(){

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
Linked List:
[ 55 40 30 22 12 ]
Linked List after deletion:
[ 55 40 30 22 ]
Deletion at a Given Position
In this deletion operation of the linked, we are deleting an element at any position of the list.

Algorithm
1. START
2. Iterate until find the current node at position in the list
3. Assign the adjacent node of current node in the list to its previous node.
4. END
Example
Following are the implementations of this operation in various programming languages −
CC++Java
#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 && temp->data == key) {

head = temp->next;

return;

// Find the key to be deleted

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

prev = temp;

temp = temp->next;

// 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:
[ 55 40 30 22 12 ]
Linked List after deletion:
[ 55 40 22 12 ]

Reverse 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.

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 −
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
Step by step process to reverse a linked list is as follows −
1 START
2. We use three pointers to perform the reversing: prev, next, head.
3. Point the current node to head and assign its next value to the prev node.
4. Iteratively repeat the step 3 for all the nodes in the list.
5. Assign head to the prev node.
Example
Following are the implementations of this operation in various programming languages −
CC++JavaPython
#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->next = prev;

prev = cur;

cur = tmp;

*head = prev;

void main(){

int k=0;

insertatbegin(12);
insertatbegin(22);

insertatbegin(30);

insertatbegin(40);

insertatbegin(55);

printf("Linked List: ");

// print list

printList();

reverseList(&head);

printf("\nReversed Linked List: ");

printList();

Output
Linked List:
[ 55 40 30 22 12 ]
Reversed Linked List:
[ 12 22 30 40 55 ]

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
1 START
2 If the list is not empty, iteratively check if the list contains the key
3 If the key element is not present in the list, unsuccessful search
4 END
Example
Following are the implementations of this operation in various programming languages −
CC++JavaPython
#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;

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);

printf("Linked List: ");

// print list

printList();

k = searchlist(30);

if (k == 1)

printf("\nElement is found");

else

printf("\nElement is not present in the list");

Output
Linked List:
[ 55 40 30 22 12 ]
Element is found

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

Algorithm
1. START
2. While the list is not empty and did not reach the end of the list, print the data in each node
3. END
Example
Following are the implementations of this operation in various programming languages −
CC++JavaPython
#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);

insertatbegin(22);

insertatbegin(30);

printf("Linked List: ");

// print list

printList();

Output
Linked List:
[ 30 22 12 ]
Applications of Linked Lists:
Linked Lists are used to implement stacks and queues.

1. It is used for the various representations of trees and graphs.


2. It is used in dynamic memory allocation( linked list of free blocks).
3. It is used for representing sparse matrices.
4. It is used for the manipulation of polynomials.
5. It is also used for performing arithmetic operations on long integers.
6. It is used for finding paths in networks.
7. In operating systems, they can be used in Memory management, process scheduling and file system.
8. Linked lists can be used to improve the performance of algorithms that need to frequently insert or
delete items from large collections of data.
9. Implementing algorithms such as the LRU cache, which uses a linked list to keep track of the most
recently used items in a cache.

Applications of Linked Lists in real world:


1. The list of songs in the music player are linked to the previous and next songs.
2. In a web browser, previous and next web page URLs are linked through the previous and next
buttons.
3. In image viewer, the previous and next images are linked with the help of the previous and next
buttons.
4. Switching between two applications is carried out by using “alt+tab” in windows and “cmd+tab” in
mac book. It requires the functionality of circular linked list.
5. In mobile phones, we save the contacts of the people. The newly entered contact details will be
placed at the correct alphabetical order. This can be achieved by linked list to set contact at correct
alphabetical position.
6. The modifications that we make in documents are actually created as nodes in doubly linked list. We
can simply use the undo option by pressing Ctrl+Z to modify the contents. It is done by the
functionality of linked list.

Advantages of Linked Lists:


Linked lists are a popular data structure in computer science, and have a number of advantages over other
data structures, such as arrays. Some of the key advantages of linked lists are:

Dynamic size: Linked lists do not have a fixed size, so you can add or remove elements as needed, without
having to worry about the size of the list. This makes linked lists a great choice when you need to work with a
collection of items whose size can change dynamically.

Efficient Insertion and Deletion: Inserting or deleting elements in a linked list is fast and efficient, as you only
need to modify the reference of the next node, which is an O(1) operation.

Memory Efficiency: Linked lists use only as much memory as they need, so they are more efficient with
memory compared to arrays, which have a fixed size and can waste memory if not all elements are used.

Easy to Implement: Linked lists are relatively simple to implement and understand compared to other data
structures like trees and graphs.

Flexibility: Linked lists can be used to implement various abstract data types, such as stacks, queues, and
associative arrays.

Easy to navigate: Linked lists can be easily traversed, making it easier to find specific elements or perform
operations on the list.
In conclusion, linked lists are a powerful and flexible data structure that have a number of advantages over
other data structures, making them a great choice for solving many data structure and algorithm problems.

Disadvantages of Linked Lists:


Linked lists are a popular data structure in computer science, but like any other data structure, they have
certain disadvantages as well. Some of the key disadvantages of linked lists are:

Slow Access Time: Accessing elements in a linked list can be slow, as you need to traverse the linked list to find
the element you are looking for, which is an O(n) operation. This makes linked lists a poor choice for situations
where you need to access elements quickly.

Pointers: Linked lists use pointers to reference the next node, which can make them more complex to
understand and use compared to arrays. This complexity can make linked lists more difficult to debug and
maintain.

Higher overhead: Linked lists have a higher overhead compared to arrays, as each node in a linked list requires
extra memory to store the reference to the next node.

Cache Inefficiency: Linked lists are cache-inefficient because the memory is not contiguous. This means that
when you traverse a linked list, you are not likely to get the data you need in the cache, leading to cache
misses and slow performance.

Extra memory required: Linked lists require an extra pointer for each node, which takes up extra memory. This
can be a problem when you are working with large data sets, as the extra memory required for the pointers
can quickly add up.

Linked list
Linked list is a linear data structure that includes a series of connected nodes. Linked list can
be defined as the nodes that are randomly stored in the memory. A node in the linked list
contains two parts, i.e., first is the data part and second is the address part. The last node of
the list contains a pointer to the null. After array, linked list is the second most used data
structure. In a linked list, every link contains a connection to another link.

Representation of a Linked list

Linked list can be represented as the connection of nodes in which each node points to the
next node of the list. The representation of the linked list is shown below -

Till now, we have been using array data structure to organize the group of elements that are
to be stored individually in the memory. However, Array has several advantages and
disadvantages that must be known to decide the data structure that will be used throughout
the program.

71.2M
1.3K
Exception Handling in Java - Javatpoint

Now, the question arises why we should use linked list over array?

Why use linked list over array?

Linked list is a data structure that overcomes the limitations of arrays. Let's first see some of
the limitations of arrays -

o The size of the array must be known in advance before using it in the program.
o Increasing the size of the array is a time taking process. It is almost impossible to
expand the size of the array at run time.
o All the elements in the array need to be contiguously stored in the memory. Inserting
an element in the array needs shifting of all its predecessors.

Linked list is useful because -

o It allocates the memory dynamically. All the nodes of the linked list are non-
contiguously stored in the memory and linked together with the help of pointers.
o In linked list, size is no longer a problem since we do not need to define its size at the
time of declaration. List grows as per the program's demand and limited to the
available memory space.

How to declare a linked list?

It is simple to declare an array, as it is of single type, while the declaration of linked list is a
bit more typical than array. Linked list contains two parts, and both are of different types, i.e.,
one is the simple variable, while another is the pointer variable. We can declare the linked list
by using the user-defined data type structure.

The declaration of linked list is given as follows -

1. struct node
2. {
3. int data;
4. struct node *next;
5. }

In the above declaration, we have defined a structure named as node that contains two
variables, one is data that is of integer type, and another one is next that is a pointer which
contains the address of next node.

Now, let's move towards the types of linked list.

Types of Linked list

Linked list is classified into the following types -

o Singly-linked list - Singly linked list can be defined as the collection of an ordered
set of elements. A node in the singly linked list consists of two parts: data part and link
part. Data part of the node stores actual information that is to be represented by the
node, while the link part of the node stores the address of its immediate successor.
o Doubly linked list - Doubly linked list is a complex type of linked list in which a node
contains a pointer to the previous as well as the next node in the sequence. Therefore,
in a doubly-linked list, a node consists of three parts: node data, pointer to the next
node in sequence (next pointer), and pointer to the previous node (previous pointer).
o Circular singly linked list - In a circular singly linked list, the last node of the list
contains a pointer to the first node of the list. We can have circular singly linked list as
well as circular doubly linked list.
o Circular doubly linked list - Circular doubly linked list is a more complex type of
data structure in which a node contains pointers to its previous node as well as the
next node. Circular doubly linked list doesn't contain NULL in any of the nodes. The
last node of the list contains the address of the first node of the list. The first node of
the list also contains the address of the last node in its previous pointer.

Types of Linked list


The following are the types of linked list:

o Singly Linked list


o Doubly Linked list
o Circular Linked list
o Doubly Circular Linked list

Singly Linked list

It is the commonly used linked list in programs. If we are talking about the linked list, it means
it is a singly linked list. The singly linked list is a data structure that contains two parts, i.e.,
one is the data part, and the other one is the address part, which contains the address of the
next or the successor node. The address part in a node is also known as a pointer.

Suppose we have three nodes, and the addresses of these three nodes are 100, 200 and 300
respectively. The representation of three nodes as a linked list is shown in the below figure:

We can observe in the above figure that there are three different nodes having address 100,
200 and 300 respectively. The first node contains the address of the next node, i.e., 200, the
second node contains the address of the last node, i.e., 300, and the third node contains the
NULL value in its address part as it does not point to any node. The pointer that holds the
address of the initial node is known as a head pointer.
The linked list, which is shown in the above diagram, is known as a singly linked list as it
contains only a single link. In this list, only forward traversal is possible; we cannot traverse in
the backward direction as it has only one link in the list.

Representation of the node in a singly linked list

1. struct node
2. {
3. int data;
4. struct node *next;
5. }

In the above representation, we have defined a user-defined structure named


a node containing two members, the first one is data of integer type, and the other one is the
pointer (next) of the node type.

Doubly linked list

As the name suggests, the doubly linked list contains two pointers. We can define the doubly
linked list as a linear data structure with three parts: the data part and the other two address
part. In other words, a doubly linked list is a list that has three parts in a single node, includes
one data part, a pointer to its previous node, and a pointer to the next node.

Suppose we have three nodes, and the address of these nodes are 100, 200 and 300,
respectively. The representation of these nodes in a doubly-linked list is shown below:

As we can observe in the above figure, the node in a doubly-linked list has two address parts;
one part stores the address of the next while the other part of the node stores
the previous node's address. The initial node in the doubly linked list has the NULL value
in the address part, which provides the address of the previous node.

Representation of the node in a doubly linked list

1. struct node
2. {
3. int data;
4. struct node *next;
5. struct node *prev;
6. }

In the above representation, we have defined a user-defined structure named a node with
three members, one is data of integer type, and the other two are the pointers, i.e., next
and prev of the node type. The next pointer variable holds the address of the next node,
and the prev pointer holds the address of the previous node. The type of both the pointers,
i.e., next and prev is struct node as both the pointers are storing the address of the node
of the struct node type.

Circular linked list

A circular linked list is a variation of a singly linked list. The only difference between
the singly linked list and a circular linked list is that the last node does not point to any
node in a singly linked list, so its link part contains a NULL value. On the other hand, the
circular linked list is a list in which the last node connects to the first node, so the link part of
the last node holds the first node's address. The circular linked list has no starting and ending
node. We can traverse in any direction, i.e., either backward or forward. The diagrammatic
representation of the circular linked list is shown below:

1. struct node
2. {
3. int data;
4. struct node *next;
5. }

A circular linked list is a sequence of elements in which each node has a link to the next node,
and the last node is having a link to the first node. The representation of the circular linked
list will be similar to the singly linked list, as shown below:

Doubly Circular linked list

The doubly circular linked list has the features of both the circular linked list and doubly
linked list.
The above figure shows the representation of the doubly circular linked list in which the last
node is attached to the first node and thus creates a circle. It is a doubly linked list also
because each node holds the address of the previous node also. The main difference between
the doubly linked list and doubly circular linked list is that the doubly circular linked list does
not contain the NULL value in the previous field of the node. As the doubly circular linked
contains three parts, i.e., two address parts and one data part so its representation is similar
to the doubly linked list.

1. struct node
2. {
3. int data;
4. struct node *next;
5. struct node *prev;
6. }

Linked List
o Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer
which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List


o The list is not required to be contiguously present in the memory. The node can reside
any where in the memory and linked together to make a list. This achieves optimized
utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?


Till now, we were using array data structure to organize the group of elements that are to be
stored individually in the memory. However, Array has several advantages and disadvantages
which must be known in order to decide the data structure which will be used throughout the
program.

Array contains following limitations:

1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand
the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using
linked list is useful because,

1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously
stored in the memory and linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory space.

Singly linked list or One way chain


Singly linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program. A node in the singly linked list consist
of two parts: data part and link part. Data part of the node stores actual information that is to
be represented by the node while the link part of the node stores the address of its immediate
successor.

One way chain or singly linked list can be traversed only in one direction. In other words, we
can say that each node contains only next pointer, therefore we can not traverse the list in
the reverse direction.

Consider an example where the marks obtained by the student in three subjects are stored in
a linked list as shown in the figure.
In the above figure, the arrow represents the links. The data part of every node contains the
marks obtained by the student in the different subject. The last node in the list is identified by
the null pointer which is present in the address part of the last node. We can have as many
elements we require, in the data part of the list.

Complexity

Data Structure Time Complexity Space Compleity

Average Worst Worst

Acces Searc Insertio Deletio Acces Searc Insertio Deletio


s h n n s h n n

Singly Linked θ(n) θ(n) θ(1) θ(1) O(n) O(n) O(1) O(1) O(n)
List

Operations on Singly Linked List


There are various operations which can be performed on singly linked list. A list of all such
operations is given below.

Node Creation

1. struct node
2. {
3. int data;
4. struct node *next;
5. };
6. struct node *head, *ptr;
7. ptr = (struct node *)malloc(sizeof(struct node *));

Insertion

The insertion into a singly linked list can be performed at different positions. Based on the
position of the new node being inserted, the insertion is categorized into the following
categories.

S Operation Description
N

1 Insertion at It involves inserting any element at the front of the list. We just need to a few
beginning link adjustments to make the new node as the head of the list.
2 Insertion at end It involves insertion at the last of the linked list. The new node can be inserted
of the list as the only node in the list or it can be inserted as the last one. Different logics
are implemented in each scenario.

3 Insertion after It involves insertion after the specified node of the linked list. We need to skip
specified node the desired number of nodes in order to reach the node after which the new
node will be inserted. .

Deletion and Traversing

The Deletion of a node from a singly linked list can be performed at different positions. Based
on the position of the node being deleted, the operation is categorized into the following
categories.

S Operation Description
N

1 Deletion at It involves deletion of a node from the beginning of the list. This is the simplest
beginning operation among all. It just need a few adjustments in the node pointers.

2 Deletion at the It involves deleting the last node of the list. The list can either be empty or full.
end of the list Different logic is implemented for the different scenarios.

3 Deletion after It involves deleting the node after the specified node in the list. we need to skip
specified node the desired number of nodes to reach the node after which the node will be
deleted. This requires traversing through the list.

4 Traversing In traversing, we simply visit each node of the list at least once in order to
perform some specific operation on it, for example, printing data part of each
node present in the list.

5 Searching In searching, we match each element of the list with the given element. If the
element is found on any of the location then location of that element is returned
otherwise null is returned. .

Linked List in C: Menu Driven Program

1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. int data;
6. struct node *next;
7. };
8. struct node *head;
9.
10. void beginsert ();
11. void lastinsert ();
12. void randominsert();
13. void begin_delete();
14. void last_delete();
15. void random_delete();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\
n");
26. printf("\[Link] in begining\[Link] at last\[Link] at any random location\[Link]
from Beginning\n
27. [Link] from last\[Link] node after specified location\[Link] for an element\
[Link]\[Link]\n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. beginsert();
34. break;
35. case 2:
36. lastinsert();
37. break;
38. case 3:
39. randominsert();
40. break;
41. case 4:
42. begin_delete();
43. break;
44. case 5:
45. last_delete();
46. break;
47. case 6:
48. random_delete();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void beginsert()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *) malloc(sizeof(struct node *));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter value\n");
76. scanf("%d",&item);
77. ptr->data = item;
78. ptr->next = head;
79. head = ptr;
80. printf("\nNode inserted");
81. }
82.
83. }
84. void lastinsert()
85. {
86. struct node *ptr,*temp;
87. int item;
88. ptr = (struct node*)malloc(sizeof(struct node));
89. if(ptr == NULL)
90. {
91. printf("\nOVERFLOW");
92. }
93. else
94. {
95. printf("\nEnter value?\n");
96. scanf("%d",&item);
97. ptr->data = item;
98. if(head == NULL)
99. {
100. ptr -> next = NULL;
101. head = ptr;
102. printf("\nNode inserted");
103. }
104. else
105. {
106. temp = head;
107. while (temp -> next != NULL)
108. {
109. temp = temp -> next;
110. }
111. temp->next = ptr;
112. ptr->next = NULL;
113. printf("\nNode inserted");
114.
115. }
116. }
117. }
118. void randominsert()
119. {
120. int i,loc,item;
121. struct node *ptr, *temp;
122. ptr = (struct node *) malloc (sizeof(struct node));
123. if(ptr == NULL)
124. {
125. printf("\nOVERFLOW");
126. }
127. else
128. {
129. printf("\nEnter element value");
130. scanf("%d",&item);
131. ptr->data = item;
132. printf("\nEnter the location after which you want to insert ");
133. scanf("\n%d",&loc);
134. temp=head;
135. for(i=0;i<loc;i++)
136. {
137. temp = temp->next;
138. if(temp == NULL)
139. {
140. printf("\ncan't insert\n");
141. return;
142. }
143.
144. }
145. ptr ->next = temp ->next;
146. temp ->next = ptr;
147. printf("\nNode inserted");
148. }
149. }
150. void begin_delete()
151. {
152. struct node *ptr;
153. if(head == NULL)
154. {
155. printf("\nList is empty\n");
156. }
157. else
158. {
159. ptr = head;
160. head = ptr->next;
161. free(ptr);
162. printf("\nNode deleted from the begining ...\n");
163. }
164. }
165. void last_delete()
166. {
167. struct node *ptr,*ptr1;
168. if(head == NULL)
169. {
170. printf("\nlist is empty");
171. }
172. else if(head -> next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nOnly node of the list deleted ...\n");
177. }
178.
179. else
180. {
181. ptr = head;
182. while(ptr->next != NULL)
183. {
184. ptr1 = ptr;
185. ptr = ptr ->next;
186. }
187. ptr1->next = NULL;
188. free(ptr);
189. printf("\nDeleted Node from the last ...\n");
190. }
191. }
192. void random_delete()
193. {
194. struct node *ptr,*ptr1;
195. int loc,i;
196. printf("\n Enter the location of the node after which you want to perform deletion \
n");
197. scanf("%d",&loc);
198. ptr=head;
199. for(i=0;i<loc;i++)
200. {
201. ptr1 = ptr;
202. ptr = ptr->next;
203.
204. if(ptr == NULL)
205. {
206. printf("\nCan't delete");
207. return;
208. }
209. }
210. ptr1 ->next = ptr ->next;
211. free(ptr);
212. printf("\nDeleted node %d ",loc+1);
213. }
214. void search()
215. {
216. struct node *ptr;
217. int item,i=0,flag;
218. ptr = head;
219. if(ptr == NULL)
220. {
221. printf("\nEmpty List\n");
222. }
223. else
224. {
225. printf("\nEnter item which you want to search?\n");
226. scanf("%d",&item);
227. while (ptr!=NULL)
228. {
229. if(ptr->data == item)
230. {
231. printf("item found at location %d ",i+1);
232. flag=0;
233. }
234. else
235. {
236. flag=1;
237. }
238. i++;
239. ptr = ptr -> next;
240. }
241. if(flag==1)
242. {
243. printf("Item not found\n");
244. }
245. }
246.
247. }
248.
249. void display()
250. {
251. struct node *ptr;
252. ptr = head;
253. if(ptr == NULL)
254. {
255. printf("Nothing to print");
256. }
257. else
258. {
259. printf("\nprinting values . . . . .\n");
260. while (ptr!=NULL)
261. {
262. printf("\n%d",ptr->data);
263. ptr = ptr -> next;
264. }
265. }
266. }
267.

Output:

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


1

Enter value
1
Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


2

Enter value?
2

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


3

Enter element value1

Enter the location after which you want to insert 1

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


8

printing values . . . . .

1
2
1

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


2

Enter value?
123

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


1

Enter value
1234
Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


4

Node deleted from the begining ...

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


5

Deleted Node from the last ...

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


6

Enter the location of the node after which you want to perform deletion
1

Deleted node 2

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


8

printing values . . . . .

1
1

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


7

Enter item which you want to search?


1
item found at location 1
item found at location 2

*********Main Menu*********

Choose one option from the following list ...

===============================================
[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] node after specified location
[Link] for an element
[Link]
[Link]

Enter your choice?


9

Advantages of Linked list

The advantages of using the Linked list are given as follows -

o Dynamic data structure - The size of the linked list may vary according to the
requirements. Linked list does not have a fixed size.
o Insertion and deletion - Unlike arrays, insertion, and deletion in linked list is easier.
Array elements are stored in the consecutive location, whereas the elements in the
linked list are stored at a random location. To insert or delete an element in an array,
we have to shift the elements for creating the space. Whereas, in linked list, instead of
shifting, we just have to update the address of the pointer of the node.
o Memory efficient - The size of a linked list can grow or shrink according to the
requirements, so memory consumption in linked list is efficient.
o Implementation - We can implement both stacks and queues using linked list.

Disadvantages of Linked list

The limitations of using the Linked list are given as follows -

o Memory usage - In linked list, node occupies more memory than array. Each node of
the linked list occupies two types of variables, i.e., one is a simple variable, and
another one is the pointer variable.
o Traversal - Traversal is not easy in the linked list. If we have to access an element in
the linked list, we cannot access it randomly, while in case of array we can randomly
access it by index. For example, if we want to access the 3rd node, then we need to
traverse all the nodes before it. So, the time required to access a particular node is
large.
o Reverse traversing - Backtracking or reverse traversing is difficult in a linked list. In
a doubly-linked list, it is easier but requires more memory to store the back pointer.

Applications of Linked list

The applications of the Linked list are given as follows -


o With the help of a linked list, the polynomials can be represented as well as we can
perform the operations on the polynomial.
o A linked list can be used to represent the sparse matrix.
o The various operations like student's details, employee's details, or product details
can be implemented using the linked list as the linked list uses the structure data type
that can hold different data types.
o Using linked list, we can implement stack, queue, tree, and other various data
structures.
o The graph is a collection of edges and vertices, and the graph can be represented as
an adjacency matrix and adjacency list. If we want to represent the graph as an
adjacency matrix, then it can be implemented as an array. If we want to represent the
graph as an adjacency list, then it can be implemented as a linked list.
o A linked list can be used to implement dynamic memory allocation. The dynamic
memory allocation is the memory allocation done at the run-time.

Operations performed on Linked list

The basic operations that are supported by a list are mentioned as follows -

o Insertion - This operation is performed to add an element into the list.


o Deletion - It is performed to delete an operation from the list.
o Display - It is performed to display the elements of the list.
o Search - It is performed to search an element from the list using the given key.

Complexity of Linked list

Now, let's see the time and space complexity of the linked list for the operations search,
insert, and delete.

1. Time Complexity

Operations Average case time complexity Worst-case time complexity

Insertion O(1) O(1)

Deletion O(1) O(1)

Search O(n) O(n)

Where 'n' is the number of nodes in the given tree.

2. Space Complexity

Operations Space complexity

Insertion O(n)

Deletion O(n)
Search O(n)

The space complexity of linked list is O(n).

Doubly Linked List


Doubly Linked List is a variation of Linked list in which navigation is possible in both ways, either forward
and backward easily as compared to Single Linked List. 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
Following are the basic operations supported by a list.
 Insertion − Adds an element at the beginning of the list.
 Deletion − Deletes an element at the beginning of the list.
 Insert Last − Adds an element at the end of the list.
 Delete Last − Deletes an element from the end of the list.
 Insert After − Adds an element after an item 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.
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
1. START
2. Create a new node with three variables: prev, data, next.
3. Store the new data in the data variable
4. If the list is empty, make the new node as head.
5. Otherwise, link the address of the existing first node to the next variable of the new node, and
assign null to the prev variable.
6. Point the head to the new node.
7. END
Example
Following are the implementations of this operation in various programming languages −
CC++
#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

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)
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
1. START
2. Check the status of the doubly linked list
3. If the list is empty, deletion is not possible
4. If the list is not empty, the head pointer is shifted to the next node.
5. END
Example
Following are the implementations of this operation in various programming languages −
CC++
#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

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 {

head->next->prev = NULL;

head = head->next;

//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("\nDoubly Linked List: ");

printList();

printf("\nList after deleting first record: ");

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)
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
1. START
2. If the list is empty, add the node to the list and point the head to it.
3. If the list is not empty, find the last node of the list.
4. Create a link between the last node in the list and the new node.
5. The new node will point to NULL as it is the new last node.
6. END
Example
Following are the implementations of this operation in various programming languages −
CC++
#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

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;

//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;

void main(){

insertFirst(1,10);

insertFirst(2,20);

insertFirst(3,30);

insertFirst(4,1);

insertLast(5,40);

insertLast(6,56);

printf("\nDoubly Linked List: ");

printList();

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

Doubly linked list


Doubly linked list is a complex type of linked list in which a node contains a pointer to the
previous as well as the next node in the sequence. Therefore, in a doubly linked list, a node
consists of three parts: node data, pointer to the next node in sequence (next pointer) ,
pointer to the previous node (previous pointer). A sample node in a doubly linked list is shown
in the figure.

A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is
shown in the following image.
In C, structure of a node in doubly linked list can be given as :

1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. }

The prev part of the first node and the next part of the last node will always contain null
indicating end in each direction.

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

In a singly linked list, we could traverse only in one direction, because each node contains
address of the next node and it doesn't have any record of its previous nodes. However,
doubly linked list overcome this limitation of singly linked list. Due to the fact that, each node
of the list contains the address of its previous node, we can find all the details about the
previous node as well by using the previous address stored inside the previous part of each
node.

Memory Representation of a doubly linked list


Memory Representation of a doubly linked list is shown in the following image. Generally,
doubly linked list consumes more space for every node and therefore, causes more expansive
basic operations such as insertion and deletion. However, we can easily manipulate the
elements of the list since the list maintains pointers in both the directions (forward and
backward).

In the following image, the first element of the list that is i.e. 13 stored at address 1. The head
pointer points to the starting address 1. Since this is the first element being added to the list
therefore the prev of the list contains null. The next node of the list resides at address 4
therefore the first node contains 4 in its next pointer.

We can traverse the list in this way until we find any node containing null or -1 in its next part.

Operations on doubly linked list


Node Creation

1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. };
7. struct node *head;

All the remaining operations regarding doubly linked list are described in the following table.

S Operation Description
N

1 Insertion at beginning Adding the node into the linked list at beginning.

2 Insertion at end Adding the node into the linked list to the end.

3 Insertion after specified Adding the node into the linked list after the specified node.
node

4 Deletion at beginning Removing the node from beginning of the list

5 Deletion at the end Removing the node from end of the list.

6 Deletion of the node Removing the node which is present just after the node containing the
having given data given data.

7 Searching Comparing each node data with the item to be searched and return the
location of the item in the list if the item found else return null.

8 Traversing Visiting each node of the list at least once in order to perform some
specific operation like searching, sorting, display, etc.

Menu Driven Program in C to implement all the operations of doubly


linked list
1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. struct node *prev;
6. struct node *next;
7. int data;
8. };
9. struct node *head;
10. void insertion_beginning();
11. void insertion_last();
12. void insertion_specified();
13. void deletion_beginning();
14. void deletion_last();
15. void deletion_specified();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\
n");
26. printf("\[Link] in begining\[Link] at last\[Link] at any random location\[Link]
from Beginning\n
27. [Link] from last\[Link] the node after the given data\[Link]\[Link]\[Link]\
n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. insertion_beginning();
34. break;
35. case 2:
36. insertion_last();
37. break;
38. case 3:
39. insertion_specified();
40. break;
41. case 4:
42. deletion_beginning();
43. break;
44. case 5:
45. deletion_last();
46. break;
47. case 6:
48. deletion_specified();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void insertion_beginning()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *)malloc(sizeof(struct node));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter Item value");
76. scanf("%d",&item);
77.
78. if(head==NULL)
79. {
80. ptr->next = NULL;
81. ptr->prev=NULL;
82. ptr->data=item;
83. head=ptr;
84. }
85. else
86. {
87. ptr->data=item;
88. ptr->prev=NULL;
89. ptr->next = head;
90. head->prev=ptr;
91. head=ptr;
92. }
93. printf("\nNode inserted\n");
94. }
95.
96. }
97. void insertion_last()
98. {
99. struct node *ptr,*temp;
100. int item;
101. ptr = (struct node *) malloc(sizeof(struct node));
102. if(ptr == NULL)
103. {
104. printf("\nOVERFLOW");
105. }
106. else
107. {
108. printf("\nEnter value");
109. scanf("%d",&item);
110. ptr->data=item;
111. if(head == NULL)
112. {
113. ptr->next = NULL;
114. ptr->prev = NULL;
115. head = ptr;
116. }
117. else
118. {
119. temp = head;
120. while(temp->next!=NULL)
121. {
122. temp = temp->next;
123. }
124. temp->next = ptr;
125. ptr ->prev=temp;
126. ptr->next = NULL;
127. }
128.
129. }
130. printf("\nnode inserted\n");
131. }
132. void insertion_specified()
133. {
134. struct node *ptr,*temp;
135. int item,loc,i;
136. ptr = (struct node *)malloc(sizeof(struct node));
137. if(ptr == NULL)
138. {
139. printf("\n OVERFLOW");
140. }
141. else
142. {
143. temp=head;
144. printf("Enter the location");
145. scanf("%d",&loc);
146. for(i=0;i<loc;i++)
147. {
148. temp = temp->next;
149. if(temp == NULL)
150. {
151. printf("\n There are less than %d elements", loc);
152. return;
153. }
154. }
155. printf("Enter value");
156. scanf("%d",&item);
157. ptr->data = item;
158. ptr->next = temp->next;
159. ptr -> prev = temp;
160. temp->next = ptr;
161. temp->next->prev=ptr;
162. printf("\nnode inserted\n");
163. }
164. }
165. void deletion_beginning()
166. {
167. struct node *ptr;
168. if(head == NULL)
169. {
170. printf("\n UNDERFLOW");
171. }
172. else if(head->next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nnode deleted\n");
177. }
178. else
179. {
180. ptr = head;
181. head = head -> next;
182. head -> prev = NULL;
183. free(ptr);
184. printf("\nnode deleted\n");
185. }
186.
187. }
188. void deletion_last()
189. {
190. struct node *ptr;
191. if(head == NULL)
192. {
193. printf("\n UNDERFLOW");
194. }
195. else if(head->next == NULL)
196. {
197. head = NULL;
198. free(head);
199. printf("\nnode deleted\n");
200. }
201. else
202. {
203. ptr = head;
204. if(ptr->next != NULL)
205. {
206. ptr = ptr -> next;
207. }
208. ptr -> prev -> next = NULL;
209. free(ptr);
210. printf("\nnode deleted\n");
211. }
212. }
213. void deletion_specified()
214. {
215. struct node *ptr, *temp;
216. int val;
217. printf("\n Enter the data after which the node is to be deleted : ");
218. scanf("%d", &val);
219. ptr = head;
220. while(ptr -> data != val)
221. ptr = ptr -> next;
222. if(ptr -> next == NULL)
223. {
224. printf("\nCan't delete\n");
225. }
226. else if(ptr -> next -> next == NULL)
227. {
228. ptr ->next = NULL;
229. }
230. else
231. {
232. temp = ptr -> next;
233. ptr -> next = temp -> next;
234. temp -> next -> prev = ptr;
235. free(temp);
236. printf("\nnode deleted\n");
237. }
238. }
239. void display()
240. {
241. struct node *ptr;
242. printf("\n printing values...\n");
243. ptr = head;
244. while(ptr != NULL)
245. {
246. printf("%d\n",ptr->data);
247. ptr=ptr->next;
248. }
249. }
250. void search()
251. {
252. struct node *ptr;
253. int item,i=0,flag;
254. ptr = head;
255. if(ptr == NULL)
256. {
257. printf("\nEmpty List\n");
258. }
259. else
260. {
261. printf("\nEnter item which you want to search?\n");
262. scanf("%d",&item);
263. while (ptr!=NULL)
264. {
265. if(ptr->data == item)
266. {
267. printf("\nitem found at location %d ",i+1);
268. flag=0;
269. break;
270. }
271. else
272. {
273. flag=1;
274. }
275. i++;
276. ptr = ptr -> next;
277. }
278. if(flag==1)
279. {
280. printf("\nItem not found\n");
281. }
282. }
283.
284. }

Output

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


8

printing values...

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


1

Enter Item value12

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


1

Enter Item value123

Node inserted

*********Main Menu*********

Choose one option from the following list ...


===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


1

Enter Item value1234

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


8

printing values...
1234
123
12

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


2
Enter value89

node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


3
Enter the location1
Enter value12345

node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


8

printing values...
1234
123
12345
12
89

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


4

node deleted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


5

node deleted

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


8

printing values...
123
12345

*********Main Menu*********

Choose one option from the following list ...


===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


6

Enter the data after which the node is to be deleted : 123

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


8

printing values...
123

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


7

Enter item which you want to search?


123
item found at location 1
*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


6

Enter the data after which the node is to be deleted : 123

Can't delete

*********Main Menu*********

Choose one option from the following list ...

===============================================

[Link] in begining
[Link] at last
[Link] at any random location
[Link] from Beginning
[Link] from last
[Link] the node after the given data
[Link]
[Link]
[Link]

Enter your choice?


9

Exited..
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, 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
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.
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
1. START
2. Check if the list is empty
3. If the list is empty, add the node and point the head to this node
4. If the list is not empty, link the existing head as the next node to the new node.
5. Make the new node as the new head.
6. END
Example
Following are the implementations of this operation in various programming languages −
CC++
#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;

printf("\n[ ");

//start from the beginning

if(head != NULL) {

while(ptr->next != ptr) {

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

ptr = ptr->next;

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) ]
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
1. START
2. If the list is empty, then the program is returned.
3. If the list is not empty, we traverse the list using a current pointer that is set to the head pointer
and create another pointer previous that points to the last node.
4. Suppose the list has only one node, the node is deleted by setting the head pointer to NULL.
5. If the list has more than one node and the first node is to be deleted, the head is set to the next
node and the previous is linked to the new head.
6. If the node to be deleted is the last node, link the preceding node of the last node to head node.
7. If the node is neither first nor last, remove the node by linking its preceding node to its
succeeding node.
8. END
Example
Following are the implementations of this operation in various programming languages −
CC++
#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(){

//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;

//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)
Display List Operation
The Display List operation visits every node in the list and prints them all in the output.

Algorithm
1. START
2. Walk through all the nodes of the list and print them
3. END
Example
Following are the implementations of this operation in various programming languages −
CC++
#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;


printf("\n[ ");

//start from the beginning

if(head != NULL) {

while(ptr->next != ptr) {

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

ptr = ptr->next;

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) ]

You might also like