0% found this document useful (0 votes)
4 views39 pages

ds module2

This document covers the fundamentals of arrays in C programming, including their declaration, accessing elements, calculating length, and various operations such as insertion, deletion, and traversal. It also discusses multidimensional arrays, parallel arrays, and their applications in implementing data structures like stacks and queues. The document provides examples and code snippets to illustrate the concepts effectively.

Uploaded by

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

ds module2

This document covers the fundamentals of arrays in C programming, including their declaration, accessing elements, calculating length, and various operations such as insertion, deletion, and traversal. It also discusses multidimensional arrays, parallel arrays, and their applications in implementing data structures like stacks and queues. The document provides examples and code snippets to illustrate the concepts effectively.

Uploaded by

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

Data Structure

YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS


Using C

UNIT II
ARRAYS
An array is a collection of similar data elements. These data elements have the same data type. The
elements of the array are stored in consecutive memory locations and are referenced by an index (also
known as the subscript). The subscript is an ordinal number which is used to identify an element of
the array.

DECLARATION OF ARRAYS
We have already seen that every variable must be declared before it is used. The same concept holds
true for array variables. An array must be declared before being used. Declaring an array
means specifying the following:
➢ Data type—the kind of values it can store, for example, int, char, float, double.
➢ Name—to identify the array.
➢ Size—the maximum number of values that the array can hold.
Arrays are declared using the following syntax:
type name[size];

ACCESSING THE ELEMENTS OF AN ARRAY


Storing related data items in a single array enables the programmers to develop concise and efficient
programs. But there is no single function that can operate on all the elements of an array. To access
all the elements, we must use a loop. That is, we can access all the elements of an array by varying the
value of the subscript into the array. But note that the subscript must be an integral value or an
expression that evaluates to an integral value., the first element of the array marks [10] can be accessed
by writing marks [0]. Now to process all the elements of the array, we use a loop

CALCULATING THE LENGTH OF AN ARRAY


The length of an array is given by the number of elements stored in it. The general formula to calculate
the length of an array is Length = upper_bound – lower_bound + 1 where upper_bound is the index
of the last element and lower_bound is the index of the first element in the array.
1
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

STORING VALUES OF ARRAYS IN MEMORY

When we declare an array, we are just allocating space for its elements; no values are stored in the
array. There are three ways to store values in an array. First, to initialize the array elements during
declaration; second, to input values for individual elements from the keyboard; third, to assign values
to individual elements. The elements of an array can be initialized at the time of declaration, just as
any other variable. When an array is initialized, we need to provide a value for every element in the
array. Arrays are initialized by writing,
type array_name[size]={list of values};
Note that the values are written within curly brackets and every value is separated by a comma. It is
a compiler error to specify more values than there are elements in the array. When we write,
int marks[5]={90, 82, 78, 95, 88};
An array with the name marks is declared that has enough space to store five elements. The first
element, that is, marks[0] is assigned value 90. Similarly, the second element of the array, that is
marks[1], is assigned 82, and so on.
2
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

OPERATIONS ON ARRAYS
There are a number of operations that can be performed on arrays. These operations include:
➢ Traversing an array
➢ Inserting an element in an array
➢ Searching an element in an array
➢ Deleting an element from an array
➢ Merging two arrays
➢ Sorting an array in ascending or descending order

TRAVERSING AN ARRAY

Traversing an array means accessing each and every element of the array for a specific purpose.
Traversing the data elements of an array A can include printing every element, counting the total
number of elements, or performing any process on these elements. Since, array is a linear data structure
(because all its elements form a sequence), traversing its elements is very simple and straightforward.
The algorithm for array traversal is

In Step 1, we initialize the index to the lower bound of the array. In Step 2, a while loop is executed.
Step 3 processes the individual array element as specified by the array name and index value. Step 4
increments the index value so that the next array element could be processed. The while loop in Step
2 is executed until all the elements in the array are processed, i.e., until I is less than or equal to the
upper bound of the array.
Write a program to read and display n numbers using an array.
#include <stdio.h>
#include <conio.h>
int main()
{
3

int i, n, arr[20];
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5

INSERTING AN ELEMENT IN AN ARRAY

If an element has to be inserted at the end of an existing array, then the task of insertion is quite simple.
We just have to add 1 to the upper_bound and assign the value. Here, we assume that the memory
space allocated for the array is still available. For example, if an array is declared to contain 10
elements, but currently it has only 8 elements, then obviously there is space to accommodate two more
elements. But if it already has 10 elements, then we will not be able to add another element to it.
4
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Data[] is an array that is declared as int Data[20]; and contains the following
values:
Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
(a) Calculate the length of the array.
(b) Find the upper_bound and lower_bound.
(c) Show the memory representation of the array.
(d) If a new data element with the value 75 has to be inserted, find its position.
(e) Insert a new data element 75 and show the memory representation after the insertion.
Solution
(a) Length of the array = number of elements
Therefore, length of the array = 10
(b) By default, lower_bound = 0 and upper_bound = 9
(c)

(d) Since the elements of the array are stored in ascending order, the new data element will be
stored after 67, i.e., at the 6th location. So, all the array elements from the 6 th position will be
moved one position towards the right to accommodate the new value
(e)

Insert an Element in the Middle of an Array


Algorithm
5
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

In the algorithm given in Fig. 3.14, in Step 1, we first initialize I with the total number of elements in
the array. In Step 2, a while loop is executed which will move all the elements having an index greater
than POS one position towards right to create space for the new element. In Step 5, we increment the
total number of elements in the array by 1 and finally in Step 6, the new value is inserted at the desired
position.
Write a program to insert a number at a given location in an array.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, num, pos, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\n Enter the number to be inserted : ");
scanf("%d", &num);
printf("\n Enter the position at which the number has to be added : ");
scanf("%d", &pos);
for(i=n–1;i>=pos;i––)
arr[i+1] = arr[i];
arr[pos] = num;
n = n+1;
printf("\n The array after insertion of %d is : ", num);
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
getch();
return 0;
}
Output
6

Enter the number of elements in the array : 5


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be added : 3
The array after insertion of 0 is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 4
arr[5] = 5

DELETING AN ELEMENT FROM AN ARRAY

Deleting an element from an array means removing a data element from an already existing array. If
the element has to be deleted from the end of the existing array, then the task of deletion is quite
simple. We just have to subtract 1 from the upper_bound. Figure 3.15 shows an algorithm to delete an
element from the end of an array.

Example: Data [] is an array that is declared as int Data[10]; and contains the following values:
Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
(a) If a data element with value 56 has to be deleted, find its position.
(b) Delete the data element 56 and show the memory representation after the deletion.
Solution
(a) Since the elements of the array are stored in ascending order, we will compare the value that
has to be deleted with the value of every element in the array. As soon as VAL = Data[I], where
7

I is the index or subscript of the array, we will get the position from which the element has to
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

be deleted. For example, if we see this array, here VAL = 56. Data[0] = 12 which is not equal
to 56. We will continue to compare and finally get the value of POS = 4.
(b)

An element from the middle of an array

The algorithm DELETE will be declared as DELETE(A, N, POS). The arguments are:
(a) A, the array from which the element has to be deleted
(b) N, the number of elements in the array
(c) POS, the position from which the element has to be deleted

Write a program to delete a number from a given location in an array.


#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, pos, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
8

printf("\nEnter the position from which the number has to be deleted : ");
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

scanf("%d", &pos);
for(i=pos; i<n–1;i++)
arr[i] = arr[i+1];
n––;
printf("\n The array after deletion is : ");
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
getch();
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the position from which the number has to be deleted : 3
The array after deletion is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 5

MULTIDIMENSIONAL ARRAYS

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in
tabular form. Data in multidimensional arrays is generally stored in row-major order in the memory.

The general form of declaring N-dimensional arrays is shown below.


Syntax:
data_type array_name[size1][size2]....[sizeN];

• data_type: Type of data to be stored in the array.


• array_name: Name of the array.
• size1, size2,…, sizeN: Size of each dimension.
9
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

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

PARALLEL ARRAYS

Parallel arrays are a group of arrays of the same size. Each element in each array at the same index
corresponds to a different characteristic of the same subject of interest.
In the example below, we store the name and age of five persons in two different arrays.
roll_no = {1, 2, 3, 4, 5}
marks = {25, 20, 18, 30, 32}
The following is a program that demonstrates parallel arrays.
Example: Parallel Array
#include<stdio.h>
int main() {
int max = 0, index = 0, i, n = 5;
int roll_no[] = {1, 2, 3, 4, 5};
int marks[] = {25, 20, 32, 30, 18};
for (int i = 0; i < n; i++) {
if (marks[i] > max) {
max = marks[i];
index = i;
}
}
printf("Roll no %d has highest marks", roll_no[index]);
return 0;
}
Output

Roll no 3 has highest marks

APPLICATIONS OF ARRAYS

Arrays are frequently used in C, as they have a number of useful applications. These applications are
• Arrays are widely used to implement mathematical vectors, matrices, and other kinds of
10

rectangular tables.
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

• Many databases include one-dimensional arrays whose elements are records.


• Arrays are also used to implement other data structures such as strings, stacks, queues, heaps,
and hash tables. We will read about these data structures in the subsequent chapters.
• Arrays can be used for sorting elements in ascending or descending order.

Sparse Matrices Representation

Sparse matrix is a matrix that has large number of elements with a zero value. In order to efficiently
utilize the memory, specialized algorithms and data structures that take advantage of the sparse
structure should be used. If we apply the operations using standard matrix structures and algorithms
to sparse matrices, then the execution will slow down and the matrix will consume large amount of
memory. Sparse data can be easily compressed, which in turn can significantly reduce memory usage.

In the above figure, we can observe a 5x4 sparse matrix containing 7 non-zero elements and 13 zero
elements. The above matrix occupies 5x4 = 20 memory space. Increasing the size of matrix will
increase the wastage space.

The tabular representation of the above matrix is given below -


11
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Polynomial representation using array


The operations such as addition, subtraction, multiplication, differentiation and so forth can be
performed on the polynomials represented as arrays.
Example:

Consider a polynomial with two variables: 2x2+5xy+y2. The array representation of the polynomial is
given below:

2 2 0 5 1 1 1 0 2

Index 0 stores the coefficient of the first term, index 1 stores the exponent of the variable x and index
2 stores the exponent of the variable y in the first term. The process is repeated for the remaining terms
in the polynomial.

LINKED LISTS

A linked list, in simple terms, is a linear collection of data elements. These data elements are called
nodes. Linked list is a data structure which in turn can be used to implement other data structures.
Thus, it acts as a building block to implement data structures such as stacks, queues, and their
variations. A linked list can be perceived as a train or a sequence of nodes in which each node contains
one or more data fields and a pointer to the next node.
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 preallocated. 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.
12
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

In Figure, we can see a linked list in which every node contains two parts, an integer and a pointer
to the next node. The left part of the node which contains data may include a simple data type, an
array, or a structure. The right part of the node contains a pointer to the next node (or address of the
next node in sequence). The last node will have no next node connected to it, so it will store a special
value called NULL. In Figure, the NULL pointer is represented by X. While programming, we usually
define NULL as –1. Hence, a NULL pointer denotes the end of the list. Since in a linked list, every
node contains a pointer to another node which is of the same type, it is also called a self-referential
data type.
we can implement a linked list using the following code:
struct node
{
int data;
struct node *next;
};
data will store the information part and next will store the address of the next node in sequence

ARRAY VS. LINKED LIST

Array Linked list

An array is a collection of elements of a similar A linked list is a collection of objects known as


data type. a node where node consists of two parts, i.e., data
and address.

Array elements store in a contiguous memory Linked list elements can be stored anywhere in
location. the memory or randomly stored.

Array works with a static memory. Here static The Linked list works with dynamic memory.
memory means that the memory size is fixed Here, dynamic memory means that the memory
and cannot be changed at the run time. size can be changed at the run time according to
our requirements.
13
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Array elements are independent of each other. Linked list elements are dependent on each
other. As each node contains the address of the
next node so to access the next node, we need to
access its previous node.

Array takes more time while performing any Linked list takes less time while performing any
operation like insertion, deletion, etc. operation like insertion, deletion, etc.

Accessing any element in an array is faster as Accessing an element in a linked list is slower as
the element in an array can be directly accessed it starts traversing from the first element of the
through the index. linked list.

In the case of an array, memory is allocated at In the case of a linked list, memory is allocated
compile-time. at run time.

Memory utilization is inefficient in the array. Memory utilization is efficient in the case of a
For example, if the size of the array is 6, and linked list as the memory can be allocated or
array consists of 3 elements only then the rest deallocated at the run time according to our
of the space will be unused. requirement.

REPRESENTATION OF LINKED LISTS IN MEMORY

In memory the linked list is stored in scattered cells (locations). The memory for each node is allocated
dynamically means as and when required. So the Linked List can increase as per the user wish and the
size is not fixed, it can vary. Suppose first node of linked list is allocated with an address 1008. Its
graphical representation looks like the figure shown below:

Suppose next node is allocated at an address 506, so the list becomes,

Suppose next node is allocated with an address with an address 10,s the list become,
14
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

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.
4. Circular Double Linked List.
SINGLE LINKED LIST.
A singly linked list is the simplest type of linked list in which every node contains some data and a
pointer to the next node of the same data type. By saying that the node contains a pointer to the next
node, we mean that the node stores the address of the next node in sequence. A singly linked list allows
traversal of data only in one way.

Operations on Singly Linked List

• Creation.
• Insertion.
• Deletion.
• Traversing.

Creating a node for Single Linked List

Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for
creating a node. The information is stored in the memory, allocated by using the malloc() function.
After allocating memory for the structure of type node, the information for the item (i.e., data) has to
be read from the user, set next field to NULL and finally returns the address of the node.
struct node
{
int data;
struct node *next;
};
node* newnode;
newnode = (node *) malloc(sizeof(node));
15

printf("\n Enter data: "); scanf("%d",


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

&newnode -> data);


newnode -> next = NULL;
INSERTION AT BEGINNING

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

Algorithm

1. Declare a head pointer and make it as NULL.

2. Create a new node with the given data.

3. Make the new node points to the head node.

4. Finally, make the new node as the head node.

Declare a head pointer and make it as NULL

struct node
{
int data;
struct node *next;
};
struct node *head = NULL;

Create a new node with the given data.

void addFirst(struct node **head, int val)


{
//create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
}

Make the newnode points to the head node

void addFirst(struct node **head, int val)


{
//create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
16

newNode->next = *head;
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Make the new node as the head node.

void addFirst(struct node **head, int val)


{
//create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = *head;
*head = newNode;
}

INSERTING A NODE AT THE END OF A LINKED LIST

Example

Input

Linked List : 10 20 30 40 NULL.

50

Output

Linked List : 10 20 30 40 50 NULL.

Input

Linked List : NULL

10

Output

Linked List : 10 NULL

Algorithm
17

1. Declare head pointer and make it as NULL.


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

2. Create a new node with the given data. And make the new node => next as NULL.
(Because the new node is going to be the last node.)
3. If the head node is NULL (Empty Linked List), make the new node as the head.
4. If the head node is not null, (Linked list already has some elements), find the last node.make the
last node => next as the new node.

1. Declare head pointer and make it as NULL.

struct node
{
int data;
struct node *next;
};
struct node *head = NULL;

2. Create a new node

void addLast(struct node **head, int val)


{
//create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
}

3. If the head node is NULL, make the new node as head

void addLast(struct node **head, int val)


{
//create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
18
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

//if head is NULL, it is an empty list


if(*head == NULL)
*head = newNode;
}

4. Otherwise, find the last node and set last node => new node

The last node of a linked list has the reference pointer as NULL. i.e. node=>next = NULL.

To find the last node, we have to iterate the linked till the node=>next != NULL.

Pseudocode

while(node->next != NULL)
{
node = node->next;
}

After that, we have to make the last node-> next as the new node. i.e. last node->next = new node;

void addLast(struct node **head, int val)


{
//create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;

//if head is NULL, it is an empty list


if(*head == NULL)
*head = newNode;
//Otherwise, find the last node and add the newNode
else
{
struct node *lastNode = *head;
//last node's next address will be NULL.
19

while(lastNode->next != NULL)
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

{
lastNode = lastNode->next;
}
//add the newNode at the end of the linked list
lastNode->next = newNode;
}
}

DELETING A NODE IN LINKED LIST

Example

Linked List : 10 20 30 NULL

Input

20

Output

10 30 NULL

Algorithm

1. If the head node has the given key,

make the head node points to the second node and free its memory.

2. Otherwise,

From the current node, check whether the next node has the given key

if yes, make the current->next = current->next->next and free the memory.

else, update the current node to the next and do the above process (from step 2) till the last node.

1. Head node has the given key

void deleteNode(struct node **head, int key)


{
//temp is used to freeing the memory
20

struct node *temp;


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

//key found on the head node.


//move to head node to the next and free the head.
if(*head->data == key)
{
temp = *head; //backup the head to free its memory
*head = (*head)->next;
free(temp);
}
}

2. For other nodes (Non-Head)

void deleteNode(struct node **head, int key)


{
//temp is used to freeing the memory
struct node *temp;
//key found on the head node.
//move to head node to the next and free the head.
if((*head)->data == key)
{
temp = *head; //backup to free the memory
*head = (*head)->next;
free(temp);
}
else
{
struct node *current = *head;
while(current->next != NULL)
{
//if yes, we need to delete the current->next node
if(current->next->data == key)
{
temp = current->next;
21

//node will be disconnected from the linked list.


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

current->next = current->next->next;
free(temp);
break;
}
//Otherwise, move the current node and proceed
else
current = current->next;
}
}
}

SEARCHING/TRAVERSING A NODE IN SINGLY LINKED LIST

Example

Linked List : 10 20 30 40 NULL.

Input

20

Output

Search Found

Algorithm

1. Iterate the linked list using a loop.

2. If any node has the given key value, return 1.

3. If the program execution comes out of the loop (the given key is not present in the linked list), return
-1.

Search Found => return 1.

Search Not Found => return -1.

1. Iterate the linked list using a loop.


22

int searchNode(struct node *head, int key)


{
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

struct node *temp = head;


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

2. Return 1 on search found

int searchNode(struct node *head, int key)


{
struct node *temp = head;
while(temp != NULL)
{
if(temp->data == key)
return 1;
temp = temp->next;
}
}

3. Return -1 on search not found

int searchNode(struct node *head, int key)


{
struct node *temp = head;
while(temp != NULL)
{
if(temp->data == key)
return 1;
temp = temp->next;
}
return -1;
}
23
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

DOUBLE LINKED LIST/ TWO-WAY LINKED LIST

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 :


struct node
{
struct node *prev;
int data;
struct node *next;
}

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

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
24
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

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.

INSERTION ON A DOUBLY LINKED LIST

Pushing a node to a doubly-linked list is similar to pushing a node to a linked list, but extra work is
required to handle the pointer to the previous node.

We can insert elements at 3 different positions of a doubly-linked list:

1. Insertion at the beginning


2. Insertion in-between nodes
25

3. Insertion at the End


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Suppose we have a double-linked list with elements 1, 2, and 3.

INSERTION AT THE BEGINNING

Let's add a node with value 6 at the beginning of the doubly linked list we made above.
1. Create a new node
• allocate memory for newNode
• assign the data to newNode.

2. Set prev and next pointers of new node


• point next of newNode to the first node of the doubly linked list
• point prev to null

3. Make new node as head node


• Point prev of the first node to newNode (now the previous head is the second node)
• Point head to newNode
26
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Code for Insertion at the Beginning

// insert node at the front


void insertFront(struct Node** head, int data) {
// allocate memory for newNode
struct Node* newNode = new Node;
// assign data to newNode
newNode->data = data;
// point next of newNode to the first node of the doubly linked list
newNode->next = (*head);
// point prev to NULL
newNode->prev = NULL;
// point previous of the first node (now first node is the second node) to newNode
if ((*head) != NULL)
(*head)->prev = newNode;
// head points to newNode
(*head) = newNode;
}

INSERTION IN BETWEEN TWO NODES

Let's add a node with value 6 after node with value 1 in the doubly linked list.

1. Create a new node


• allocate memory for newNode
• assign the data to newNode.

2. Set the next pointer of new node and previous node


• assign the value of next from previous node to the next of newNode
• assign the address of newNode to the next of previous node
27
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

3. Set the prev pointer of new node and the next node
• assign the value of prev of next node to the prev of newNode
• assign the address of newNode to the prev of next node

The final doubly linked list is after this insertion is:

CODE FOR INSERTION IN BETWEEN TWO NODES


// insert a node after a specific node
void insertAfter(struct Node* prev_node, int data) {

// check if previous node is NULL


if (prev_node == NULL) {
cout << "previous node cannot be NULL";
return;
}
28

// allocate memory for newNode


Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

struct Node* newNode = new Node;

// assign data to newNode


newNode->data = data;

// set next of newNode to next of prev node


newNode->next = prev_node->next;

// set next of prev node to newNode


prev_node->next = newNode;

// set prev of newNode to the previous node


newNode->prev = prev_node;

// set prev of newNode's next to newNode


if (newNode->next != NULL)
newNode->next->prev = newNode;
}

INSERTION AT THE END

Let's add a node with value 6 at the end of the doubly linked list.

1. Create a new node

2. Set prev and next pointers of new node and the previous node
If the linked list is empty, make the newNode as the head node. Otherwise, traverse to the end of the
doubly linked list and
29
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

The final doubly linked list looks like this.

Code for Insertion at the End


// insert a newNode at the end of the list
void insertEnd(struct Node** head, int data) {
// allocate memory for node
struct Node* newNode = new Node;

// assign data to newNode


newNode->data = data;

// assign NULL to next of newNode


newNode->next = NULL;

// store the head node temporarily (for later use)


struct Node* temp = *head;

// if the linked list is empty, make the newNode as head node


if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return;
30

}
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

// if the linked list is not empty, traverse to the end of the linked list
while (temp->next != NULL)
temp = temp->next;
// now, the last node of the linked list is temp
// point the next of the last node (temp) to newNode.
temp->next = newNode;
// assign prev of newNode to temp
newNode->prev = temp;
}

DELETION FROM A DOUBLY LINKED LIST

Similar to insertion, we can also delete a node from 3 different positions of a doubly linked list.
Suppose we have a double-linked list with elements 1, 2, and 3.

1. Delete the First Node of Doubly Linked List

If the node to be deleted (i.e. del_node) is at the beginning


Reset value node after the del_node (i.e. node two)

Finally, free the memory of del_node. And, the linked will look like this
31
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Code for Deletion of the First Node


if (*head == del_node)
*head = del_node->next;
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
free(del);

DELETION OF THE INNER NODE

If del_node is an inner node (second node), we must have to reset the value of next and prev of the
nodes before and after the del_node.
For the node before the del_node (i.e. first node)
Assign the value of next of del_node to the next of the first node.
For the node after the del_node (i.e. third node)
Assign the value of prev of del_node to the prev of the third node.

Finally, we will free the memory of del_node. And, the final doubly linked list looks like this.

Code for Deletion of the Inner Node


if (del_node->next != NULL)
del_node->next->prev = del_node->prev;

if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
32
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

3. Delete the Last Node of Doubly Linked List

In this case, we are deleting the last node with value 3 of the doubly linked list.
Here, we can simply delete the del_node and make the next of node before del_node point
to NULL.

The final doubly linked list looks like this.

Code for Deletion of the Last Node

if (del_node->prev != NULL)

del_node->prev->next = del_node->next;

Here, del_node ->next is NULL so del_node->prev->next = NULL.

SINGLY LINKED LIST VS DOUBLY LINKED LIST

Singly Linked List Doubly Linked List

Each node consists of a data value Each node consists of a data value, a pointer to the
and a pointer to the next node. next node, and a pointer to the previous node.

Traversal can occur in one way only


Traversal can occur in both ways.
(forward direction).
33
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

It requires less space. It requires more space because of an extra pointer.

It has multiple usages. It can be implemented on the


It can be implemented on the stack.
stack, heap, and binary tree.

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.

Representation of Circular Linked List

Let's see how we can represent a circular linked list on an algorithm/code. Suppose we have a linked
list:
34
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

Here, the single node is represented as

struct Node {
int data;
struct Node * next;
};
Each struct node has a data item and a pointer to the next struct node.

Now we will create a simple circular linked list with three items to understand how this works.
/* Initialize nodes */
struct node *last;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

/* Assign data values */


one->data = 1;
two->data = 2;
three->data = 3;

/* Connect nodes */
one->next = two;
two->next = three;
35

three->next = one;
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

/* Save address of third node in last */


last = three;
In the above code, one, two, and three are the nodes with data items 1, 2, and 3 respectively.

For node one


• next stores the address of two (there is no node before it)
For node two
• next stores the address of three
For node three
• next stores NULL (there is no node after it)
• next points to node one
Insertion on a Circular Linked List

We can insert elements at 3 different positions of a circular linked list:

1. Insertion at the beginning


2. Insertion in-between nodes
3. Insertion at the end
Suppose we have a circular linked list with elements 1, 2, and 3.

Let's add a node with value 6 at different positions of the circular linked list we made above. The first
step is to create a new node.

• allocate memory for newNode


• assign the data to newNode
36
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

INSERTION AT THE BEGINNING

• store the address of the current first node in the newNode (i.e. pointing the newNode to the
current first node)
• point the last node to newNode (i.e making newNode as head)

INSERTION IN BETWEEN TWO NODES

Let's insert newNode after the first node.

• travel to the node given (let this node be p)


• point the next of newNode to the node next to p
• store the address of newNode at next of p
37
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

INSERTION AT THE END

• store the address of the head node to next of newNode (making newNode the last node)
• point the current last node to newNode
• make newNode as the last node

DELETION ON A CIRCULAR LINKED LIST

Suppose we have a double-linked list with elements 1, 2, and 3.

1. If the node to be deleted is the only node

• free the memory occupied by the node

• store NULL in last


2. If last node is to be deleted

• find the node before the last node (let it be temp)


• store the address of the node next to the last node in temp
• free the memory of last

• make temp as the last node


38
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C

3. If any other nodes are to be deleted

• travel to the node to be deleted (here we are deleting node 2)

• let the node before node 2 be temp


• store the address of the node next to 2 in temp
• free the memory of 2

HEADER LINKED LIST

A header linked list is a type of linked list that has a header node at the beginning of the list. In a
header linked list, HEAD points to the header node instead of the first node of the list.

The header node does not represent an item in the linked list. This data part of this node is generally
used to hold any global information about the entire linked list. The next part of the header node points
to the first node in the list.
39
Page

You might also like