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

Array

Ds unit 1 aktu

Uploaded by

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

Array

Ds unit 1 aktu

Uploaded by

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

Array

An array is a list of a finite number ‘n’ of homogeneous data element such that The elements of the array are
reference respectively by an index set consisting of n consecutive numbers.
The element of the array are respectively in successive memory locations. The number n of elements is called
the length or size of the array. The length or the numbers of elements of the array can be obtained from the
index set by the formula When LB = 0,
Length = UB – LB + 1
When LB = 1,
Length = UB
Where,
UB is the largest index called the Upper Bound
LB is the smallest index, called the Lower Bound

Representation of linear arrays in memory

Let LA be a linear array in the memory of the computer. The memory of the computer is simply a
sequence of address location as shown below,

1000
1001
1002
1003
1004

LOC (LA [K]) = address of the element LA [K] of the array LA. The elements of LA are stored in successive
memory cells.
The computer does not keep track of the address of every element of LA, but needs to keep track only the
address of the first element of LA denoted by, LA[0]
Using the base address of LA, the computer calculates the address of any element of LA by the formula
LOC (LA[K]) = Base Address + w (Size of elements)(K – lower bound)
Where, w is the number of words per memory cell for the array LA.

ARRAY OPERATIONS
1. Traversing
Let A be a collection of data elements stored in the memory of the computer. Suppose if the contents of the
each elements of array A needs to be printed or to count the numbers of elements of A with a given property
can be accomplished by Traversing.
Traversing is a accessing and processing each element in the array exactly once.

Algorithm 1: (Traversing a Linear Array)


Hear LA is a linear array with the lower bound LB and upper bound UB. This algorithm traverses LA
applying an operation PROCESS to each element of LA using while loop.
1. [Initialize Counter] set K:= LB
2. Repeat step 3 and 4 while K ≤ UB
3. [Visit element] Apply PROCESS to LA [K]
4. [Increase counter] Set K:= K + 1
[End of step 2 loop]
5. Exit Program

Program:

#include<stdio.h>
#include<conio.h> int main()
{
int A[100],K=0,UB;
printf(“Enter the Array size less than 100: “);
printf(“Enter the elements in array: \n”);
for(K=0;K<UB;K++)
{
scanf(“%d”,&A[K]);
}
printf(“The Traverse of array is:\n”);
for(K=0;K<UB;K++)
{
printf(“%d\n”,A[K]);
}
getch();
return 0;
}

2. Inserting

➢ Let A be a collection of data elements stored in the memory of the computer.


➢ Inserting refers to the operation of adding another element to the collection A.
➢ Inserting an element at the “end” of the linear array can be easily done provided the memory space
allocated for the array is large enough to accommodate the additional element.
➢ Inserting an element in the middle of the array, then on average, half of the elements must be moved
downwards to new locations to accommodate the new element and keep the order of the other elements.
Algorithm:
INSERT (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K ≤ N.
This algorithm inserts an element ITEM into the Kt h position in LA.
1. [Initialize counter] set J:= N
2. Repeat step 3 and 4 while J ≥ K
th
3. [Move J element downward] Set LA [J+1] := LA[J]
4. [Decrease counter] set J:= J – 1
[End of step 2 loop]
5. [Insert element] set LA[K]:= ITEM
6. [Reset N] set N:= N+1
7. Exit

Program:
#include <stdio.h>
int main()
{
int array[100], position, c, n, value; printf("Enter number of
elements in array\n"); scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++)
printf("%d\n", array[c]);
return 0;
}.

Deleting
➢ Deleting refers to the operation of removing one element to the collection A.
➢ Deleting an element at the “end” of the linear array can be easily done with difficulties.
➢ If element at the middle of the array needs to be deleted, then each subsequent elements be moved one
location upward to fill up the array.
Algorithm

DELETE (LA, N, K, ITEM)


Here LA is a linear array with N elements and K is a positive integer such that K ≤ N. this algorithm deletes
the Kt h element from LA
1. Set ITEM:= LA[K]
2. Repeat for J = K to N – 1
[Move J + 1 element upward] set LA[J]:= LA[J+1]
[End of loop]
3. [Reset the number N of elements in LA] set N:= N – 1
4. Exit
program
#include <stdio.h>
int main()
{
int array[100], position, c, n;
printf("Enter number of elements in array\n"); canf("%d", &n);+
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if (position >= n+1)
printf("Deletion not possible.\n");
else
{
for (c = position - 1; c < n - 1; c++)
array[c] = array[c+1];
printf("Resultant array:\n");
for (c = 0; c < n - 1; c++)
printf("%d\n", array[c]);
}
return 0; }
Multidimensional Arrays
In C, we can define multidimensional arrays in simple words as array of arrays. Data in multidimensional
arrays are stored in tabular form (in row-major order). General form of declaring N-dimensional arrays:

data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array. Here data_type is valid C data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions

Examples:

Two dimensional array: int two_d[10][20];


Three dimensional array: int three_d[10][20][30];

Size of multidimensional arrays


Total number of elements that can be stored in a multidimensional array can be calculated by multiplying the
size of all the dimensions. For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

Example : Sum of two matrices using Two dimensional arrays

// C program to find the sum of two matrices of order 2*2


#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter a%d%d: ", i+1, j+1);
scanf("%f", &a[i][j]);
}

//Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter b%d%d: ", i+1, j+1);
scanf("%f", &b[i][j]);
}
adding corresponding elements of two arrays
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}
//Displaying the sum
printf("\nSum Of Matrix:");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("%.1f\t", c[i][j]);
if(j==1)
printf("\n");
}
return 0;
}

Ouput:

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;
Sum Of Matrix:
2.2 0.5
-0.9 25.0

Representation of 2D arrays in memory


A 2D array’s elements are stored in continuous memory locations. It can be represented in memory using any
of the following two ways:
1. Column-Major Order
2. Row-Major Order

1. Column-Major Order:

In this method the elements are stored column wise, i.e. m elements of first column are stored in first m
locations, m elements of second column are stored in next m locations and so on. E.g.
A 3 x 4 array will stored as below:
2. Row-Major Order:

In this method the elements are stored row wise, i.e. n elements of first row are stored in first n locations, n
elements of second row are stored in next n locations and so on. E.g.
A 3 x 4 array will stored as below:

Address Calculation in Double (Two) Dimensional Array:


While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations.
Therefore, a 2-D array must be linearized so as to enable their storage. There are two alternatives to achieve
linearization: Row-Major and Column-Major.

Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:

(1) Row Major System (2) Column Major System


Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = BA + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:

The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = BA + W * [( I – Lr ) + M * ( J – Lc )] Where,

B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found W = Storage Size of one element stored in the
array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of rows of the given matrix
N = Number of columns of the given matrix.

Calculation of address of element of 1-D, 2-D, and 3-D using row-major and
column-major order
Calculating the address of any element In the 1-D array:
A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its elements involves a
single subscript that can either represent a row or column index.
Example:

1-D array

To find the address of an element in an array the following formula is used-


Address of A[I] = B A+ W * (I – LB)
I = Subset of element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).
Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the size of each element is
2 bytes in the memory, find the address of A[1700].
Solution:
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
Formula used:
Address of A[I] = BA + W * (I – LB)
Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
Calculate the address of any element in the 2-D array:
The 2-dimensional array can be defined as an array of arrays. The 2-Dimensional arrays are organized as
matrices which can be represented as the collection of rows and columns as array[M][N] where M is the
number of rows and N is the number of columns.
Example:

2-D array

To find the address of any element in a 2-Dimensional array there are the following two ways-
1. Row Major Order
2. Column Major Order
1. Row Major Order:
Row major ordering assigns successive elements, moving across the rows and then down the next row, to
successive memory locations. In simple language, the elements of an array are stored in a Row-Wise fashion.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = BA + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,

J = Column Subset of an element whose address to be found,


B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.

Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1
Byte in memory. Find the address of arr[8][6] with the help of row-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210

2. Column Major Order:


If elements of an array are stored in a column-major fashion means moving across the column and then to the
next column then it’s in column-major order. To find the address of the element using column-major order use
the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.

Example: Given an array arr[1………10][1………15] with a base value of 100 and the size of each element
is 1 Byte in memory find the address of arr[8][6] with the help of column-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = BA + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
From the above examples, it can be observed that for the same position two different address locations are
obtained that’s because in row-major order movement is done across the rows and then down to the next row,
and in column-major order, first move down to the first column and then next column. So both the answers are
right.
So it’s all based on the position of the element whose address is to be found for some cases the same answers
is also obtained with row-major order and column-major order and for some cases, different answers are
obtained.

Calculate the address of any element in the 3-D Array:


A 3-Dimensional array is a collection of 2-Dimensional arrays. It is specified by using three subscripts:
1. Block size
2. Row size
3. Column size
More dimensions in an array mean more data can be stored in that array.
Example:
3-D array

To find the address of any element in 3-Dimensional arrays there are the following two ways-
• Row Major Order
• Column Major Order

1. Row Major Order:
To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = BA + W *(P * N * (i-x) +P *(j-y) + (k-z))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width

Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each element is 2
Bytes in memory find the address of element arr[5][-1][8] with the help of row-major order?
Solution: Given:
Block Subset of an element whose address to be found I = 5
Row Subset of an element whose address to be found J = -1
Column Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -4
Lower Limit of column/start column index of matrix z = 5
M(row) = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N(Column)= Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6

Formula used:
Address of A[i][j][k] = BA + W *(P * N * (i-x) +P *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * (6*6*4)+(6*3)+3
= 400 + 2 * (165)
= 730

2. Column Major Order:


To find the address of the element using column-major order, use the following formula:1
Address of A[i][j][k]= BA + W(M * N(k – z) + M *( j – y) + (i-x))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of block (first subscipt)
y = Lower Bound of Row
z = Lower Bound of Column

Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each element is 4
Bytes in memory find the address of element arr[3][3][3] with the help of column-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -5
Lower Limit of column/start column index of matrix z = -10
M (row)= Upper Bound – Lower Bound + 1 = 8 -1+1 = 8
N (column)= Upper Bound – Lower Bound + 1 = 5 + 5 + 1 = 11
Formula used:
Address of A[i][j][k]= BA + W(M * N(k – z) + M *( j – y) + (i-x))
Solution:
Address of arr[3][3][3] = 400 + 4 * ((11*8*(3-1)+8*(3-(-5)+(3-(-10)))
= 400 + 4 * ((88*2 + 8*8 + 13)
= 400 + 4 * (253) = 400 + 1012 = 1412

Calculating the address of an element in an N-dimensional array


N-Dimensional Arrays: The N-Dimensional array is basically an array of arrays. As 1-D arrays are identified
as a single index, 2-D arrays are identified using two indices, similarly, N-Dimensional arrays are identified
using N indices. A multi-dimensional array is declared as follows:
int NDA[L1][L2][L3]……..[LN];

Address Calculation of N-Dimensional Arrays:

There exist two ways to store the array elements:


• Row Major
• Column Major
The Column Major formula:
Address of N-Dimensional A[I1][I2]. . . [IN] = BA + W*[((…ENLN-1+ EN-1 )LN-2 +… E3 )L2+ E2 )L1 +E1]
Also, Ei is given by Ei = li – Lower bound, where li is the calculated indexes (indices of array element which
need to be determined) and Li=UB-LB+1
The Row Major formula:
Address of N-Dimensional A[I1][I2]. . . [IN] = BA + W*[((E1L2 + E2 )L3 +E3 )L4 ….. + EN-1 )LN + EN]
The simplest way to learn the formulas:
((((E1S2 + E2)S3 + E3)S4 + E4)S5 + E5).

Example: Let’s take a multi-dimensional array A[10][20][30][40] with the base address 1200. The task is to
find the address of element A[1][3][5][6].
Here, BAd = 1200 and width = 4.
L1 = 10, L2 = 20, L3 = 30, L4 = 40
Since the lower bounds are not given, so lower bounds are assumed to be zero.
E1 = 1 – 0 = 1;
E2 = 3 – 0 = 3;
E3 = 5 – 0 = 5;
E4 = 6 – 0 = 6.
Any of the techniques (Row-major or column-major) can be used for calculating the answer (unless
specified).
By applying the formula for row-major, directly write the formula as:
A[1][3][5][6] = 1200 + 4(((1 × 20 + 3)30 +5)40 + 6)
=1200 +4((23 × 30 +5)40 +6)
=1200 + 4(695 × 40 + 6)
=1200 + (4 × 27806)
=112424.

Sparse Matrix and its representations


•••
A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values.
If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix ?
• Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only
those elements.
• Computing time: Computing time can be saved by logically designing a data structure traversing only
non-zero elements.
Example:
00304
00570
00000
02600
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of
no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero
elements. This means storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common representations:
1. Array representation
2. Linked list representation
1: Using Arrays:
2D array is used to represent a sparse matrix in which there are three rows named as
• Row: Index of row, where non-zero element is located
• Column: Index of column, where non-zero element is located
• Value: Value of the non zero element located at index – (row,column)

Implementation:
// C++ program for Sparse Matrix Representation
// using Array
#include<stdio.h>

int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;

// number of columns in compact Matrix (size) must be


// equal to number of non - zero elements in
// sparse Matrix
int compactMatrix[3][size];

// Making of new matrix


int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}

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


{
for (int j=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);

printf("\n");
}
return 0;
}

Function for Dynamic memory allocation:


The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic
means the memory is allocated during runtime (execution of the program) from the heap segment.

Initialization

malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the
block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory
without first initializing it, then you will invoke undefined behavior, which usually means the values you
read will be garbage values
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read
the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0
by calloc().

Parameters

malloc() takes a single argument, which is the number of bytes to allocate.


Unlike malloc(), calloc() takes two arguments:
1. Number of blocks to be allocated.
2. Size of each block in bytes.

Return Value

After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise
NULL is returned which indicates failure.
Difference between malloc() and calloc() in C

S.No. malloc() calloc()


1 malloc() is a function that creates one block calloc() is a function that assigns a specified
of memory of a fixed size. number of blocks of memory to a single variable
2 malloc() only takes one argument calloc() takes two arguments.
3 malloc() is faster than calloc. calloc() is slower than malloc()
4 malloc() has high time efficiency calloc() has low time efficiency
5 malloc() is used to indicate memory calloc() is used to indicate contiguous memory
allocation allocation
6 malloc() does not initialize the memory to calloc() initializes the memory to zero
zero
7 malloc() does not add any extra memory calloc() adds some extra memory overhead
overhead

Linked List
A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every data item in a
linked list, there is an associated pointer that would give the memory location of the next data item in the linked
list.
The data items in the linked list are not in consecutive memory locations. They may be anywhere, but the
accessing of these data items is easier as each data item contains the address of the next data item.
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a program.
2. Linked lists have efficient memory utilization. Here, memory is not pre- allocated. Memory is allocated
whenever it is required and it is de- allocated (removed) when it is no longer needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a data item at a
specified position and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1. It consumes more space because every node requires a additional pointer to store address of the next node.
2. Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:
Basically we can put linked lists into the following four items:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.

Comparison between array and linked list:

Single linked list is one in which all nodes are linked together in some sequential manner. Hence, it is also
called as linear linked list.
A double linked list is one in which all nodes are linked together by multiple links which helps in accessing
both the successor node (next node) and predecessor node (previous node) from any arbitrary node within the
list. Therefore each node in a double-linked list has two link fields (pointers) to point to the left node (previous)
and the right node (next). This helps to traverse in the forward direction and backward direction.
A circular linked list is one, which has no beginning and no end. A single linked list can be made a circular
linked list by simply storing address of the very first node in the link field of the last node.

Single Linked List:


A linked list allocates space for each element separately in its own block of memory called a "node". The list gets an
overall structure by using pointers to connect all its nodes together like the links in a chain.
Each node contains two fields; a "data" field to store what eve r element, and a "next" field which is a pointer
used to link to the next node.
Each node is allocated in the heap using malloc(), so the node memory continues to exist until it is explicitly
de-allocated using free(). The front of the list is a pointer to the “start” node. A single linked list is shown in
figure.
The beginning of the linked list is stored in a " start " pointer which points to the first node. The first node
contains a pointe r to the second node.
The second node contains a pointer to the third node, ... and so on. The last node in the list has its next field set
to NULL to mark the end of the list. Code can access any node in the list by star ting at the start and following
the next pointers .
The start pointer is an ordinary local pointe r variable, so it is drawn separately on the left top to show that it is
in the stack. The list nodes are drawn on the right to show that they are allocated in the heap.

The basic operations in a single linked list are:


➢ Creation.
➢ Insertion.
➢ Deletion.
➢ Traversing.

Traversing a Linked List


Suppose we want to traverse LIST in order to process each node exactly once. The traversing algorithm uses a
pointer variable PTR which points to the node that is currently being processed. Accordingly, PTR->NEXT
points to the next node to be processed so,

PTR=HEAD [ Moves the pointer to the first node of the list]


PTR=PTR->NEXT [ Moves the p
ointer to the next node in the list.]

Program
void display()
1. {
2. struct node *ptr;
3. ptr = head;
4. if(ptr == NULL)
5. printf("Nothing to print");
6. else
7. {
8. printf("\nprinting values . . . . .\n");
9. while (ptr!=NULL)
10. {
11. printf("\n%d",ptr->data);
12. ptr = ptr -> next;
13. } }}

You might also like