0% found this document useful (0 votes)
7 views95 pages

Data Structures 1st and 2nd Week

The document outlines a series of programming experiments focused on array manipulation using C, including reversing an array, implementing linear and binary search algorithms, and sorting techniques such as bubble, selection, and insertion sort. It provides detailed algorithms, time and space complexity analyses, and example code for each experiment. The document aims to educate readers on fundamental programming concepts related to arrays and their manipulation.

Uploaded by

lokeshsivarathri
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)
7 views95 pages

Data Structures 1st and 2nd Week

The document outlines a series of programming experiments focused on array manipulation using C, including reversing an array, implementing linear and binary search algorithms, and sorting techniques such as bubble, selection, and insertion sort. It provides detailed algorithms, time and space complexity analyses, and example code for each experiment. The document aims to educate readers on fundamental programming concepts related to arrays and their manipulation.

Uploaded by

lokeshsivarathri
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/ 95

WEEK - 1

LIST OF EXPERIMENTS :
Array Manipulation:

i) Write a program to reverse an array.


ii) C Programs to implement the SearchingTechniques–Linear&BinarySearch
iii) CProgramstoimplementSortingTechniques–
Bubble,SelectionandInsertionSort

Footer 1
Array Manipulation
i) Write a program to reverse an array.

Statement :
Reversing an array means changing the order of elements so that the first
element becomes the last element and the second element becomes the second
last element and so on.

Caption

Complexity Analysis :
• Time complexity: O(n), where n is the number of elements in the array.
• Auxiliary space: O(1).

Algorithm :
1. Start .
2. Initialize two variables start = 0 as starting index and end = n-1 as
the end index .
3. Swap arr[start] and arr[end] till the start index is less than the end
index.
4. Update the start index as start + 1 and the end index as end – 1.
5. Stop.

Expected Output :

Footer 2
123456
Reversed array is
654321

Program :
// Iterative C program to reverse an array
#include <stdio.h>

/* Function to reverse arr[] from start to end*/


void rvereseArray(int arr[], int start, int end)
{
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

/* Utility that prints out an array on a line */


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);

printf("\n");
}

/* Driver function to test above functions */


int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
rvereseArray(arr, 0, n - 1);
printf("Reversed array is \n");
printArray(arr, n);
return 0;
}

Footer 3
Output :
23811A4249

123456
Reversed array is
654321

Footer 4
Output :
23811A4229

123456
Reversed array is
654321

Footer 5
ii) C Programs to implement the SearchingTechniques–
Linear&BinarySearch.

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

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

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


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

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

The steps used in the implementation of Linear Search are listed


as follows -

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


◦ In each iteration of for loop, compare the search element with the current
array element, and -
◦ If the element matches, then return the index of the corresponding
array element.
◦ If the element does not match, then move to the next element.
◦ If there is no match or the search element is not present in the given array,
return -1.
Now, let's see the algorithm of linear search.

Algorithm :
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n

Footer 6
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: stop.
Expected output :

Working of Linear search :

Now, let's see the working of the linear search Algorithm.

To understand the working of linear search algorithm, let's take an unsorted


array. It will be easy to understand the working of linear search with an
example.

Let the elements of array are-

Let the element to be searched is K = 41

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

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

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

1. Time Complexity :

Time Complexity
Case

Footer 8
Best Case O(1)
Average Case O(n)
Worst Case O(n)
◦ Best Case Complexity - In Linear search, best case occurs when the
element we are finding is at the first position of the array. The best-case
time complexity of linear search is O(1).
◦ Average Case Complexity - The average case time complexity of linear
search is O(n).
◦ Worst Case Complexity - In Linear search, the worst case occurs
when the element we are looking is present at the end of the
array. The worst-case in linear search could be when the target
element is not present in the given array, and we have to traverse
the entire array. The worst-case time complexity of linear search is
O(n).
The time complexity of linear search is O(n) because every element
in the array is compared only once.

2. Space Complexity :

O(1)
Space Complexity
◦ The space complexity of linear search is O(1).

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

Footer 9
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}

Output:
23811A4249

Footer 10
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}

Output:
23811A4229

Footer 11
Binary search :
Searching is the process of finding some particular element in the list.
If the element is present in the list, then the process is called successful, and the
process returns the location of that element. Otherwise, the search is called
unsuccessful.
Linear Search and Binary Search are the two popular searching techniques.
Here we will discuss the Binary Search Algorithm.

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

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

Algorithm :

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


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

Footer 12
Expected output:

Working of Binary search :

Now, let's see the working of the Binary Search Algorithm.

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

There are two methods to implement the binary search algorithm -

◦ Iterative method.
◦ Recursive method.
The recursive method of binary search follows the divide and conquer approach.

Let the elements of array are

Let the element to search is, K = 56

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

mid = (beg + end)/2


So, in the given array -

beg = 0

end = 8

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

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

Binary Search complexity :

Now, let's see the time complexity of Binary search in the best case, average
case, and worst case. We will also see the space complexity of Binary search.

1. Time Complexity :

Time Complexity
Case
Best Case O(1)
Average Case O(logn)
Worst Case O(logn)
◦ Best Case Complexity - In Binary search, best case occurs when the
element to search is found in first comparison, i.e., when the first

Footer 14
middle element itself is the element to be searched. The best-case time
complexity of Binary search is O(1).
◦ Average Case Complexity - The average case time complexity of Binary
search is O(logn).
◦ Worst Case Complexity - In Binary search, the worst case occurs, when
we have to keep reducing the search space till it has only one element.
The worst-case time complexity of Binary search is O(logn).
2. Space Complexity :

O(1)
Space Complexity
◦ The space complexity of binary search is O(1).

Program :
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid+1;
}
/
* if the item to be searched is smaller than middle, then it can only be in left sub
array */
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/
* if the item to be searched is greater than middle, then it can only be in right su
barray */
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}

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

Output :
23811A4249

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

Output :
23811A4229

Footer 17
iii) CProgramstoimplementSortingTechniques–
Bubble,SelectionandInsertionSort

Bubble sort :
The working procedure of bubble sort is simplest. This
article will be very helpful and interesting to students as they might
face bubble sort as a question in their examinations. So, it is important
to discuss the topic.

Bubble sort works on the repeatedly swapping of adjacent elements


until they are not in the intended order. It is called bubble sort because
the movement of array elements is just like the movement of air
bubbles in the water. Bubbles in water rise up to the surface; similarly,
the array elements in bubble sort move to the end in each iteration.

Although it is simple to use, it is primarily used as an educational tool


because the performance of bubble sort is poor in the real world. It is
not suitable for large data sets. The average and worst-case
complexity of Bubble sort is O(n2), where n is a number of items.

Bubble short is majorly used where -

◦ complexity does not matter


◦ simple and shortcode is preferred

Algorithm :

In the algorithm given below, suppose arr is an array of n elements. The


assumed swap function in the algorithm will swap the values of given array
elements.

begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort

Footer 18
Expected output :

Working of Bubble sort Algorithm :

Now, let's see the working of Bubble sort Algorithm.

To understand the working of bubble sort algorithm, let's take an unsorted array.
We are taking a short and accurate array, as we know the complexity of bubble
sort is O(n2).

Let the elements of array are -

First pass :

Sorting will start from the initial two elements. Let compare them to check
which is greater.

Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32
with 26.

Here, 26 is smaller than 36. So, swapping is required. After swapping new array
will look like -

Footer 19
Now, compare 32 and 35.

Here, 35 is greater than 32. So, there is no swapping required as they are already
sorted.

Now, the comparison will be in between 35 and 10.

Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now,
we reach at the end of the array. After first pass, the array will be -

Now, move to the second iteration.

Second Pass :

The same process will be followed for second iteration.

Footer 20
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array
will be -

Now, move to the third iteration.

Third Pass :

The same process will be followed for third iteration.

Here, 10 is smaller than 26. So, swapping is required. After swapping, the array
will be -

Now, move to the fourth iteration.

Fourth pass :

Footer 21
Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.

Bubble sort complexity :

Now, let's see the time complexity of bubble sort in the best case, average case,
and worst case. We will also see the space complexity of bubble sort.

Time Complexity :

Time Complexity
Case

Best Case O(n)


Average Case O(n2)
Worst Case O(n2)
◦ Best Case Complexity - It occurs when there is no sorting required, i.e.
the array is already sorted. The best-case time complexity of bubble sort
is O(n).
◦ Average Case Complexity - It occurs when the array elements are in
jumbled order that is not properly ascending and not properly descending.
The average case time complexity of bubble sort is O(n2).
◦ Worst Case Complexity - It occurs when the array elements are required
to be sorted in reverse order. That means suppose you have to sort the
array elements in ascending order, but its elements are in descending
order. The worst-case time complexity of bubble sort is O(n2).
Space Complexity :

O(1)
Space Complexity
Stable YES
◦ The space complexity of bubble sort is O(1). It is because, in bubble sort,
an extra variable is required for swapping.
◦ The space complexity of optimized bubble sort is O(2). It is because two
extra variables are required in optimized bubble sort.

Footer 22
Program :
#include<stdio.h>
void print(int a[], int n) //function to print array elements
{
int i;
for(i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
}
void bubble(int a[], int n) // function to implement bubble sort
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void main ()
{
int i, j,temp;
int a[5] = { 10, 35, 32, 13, 26};
int n = sizeof(a)/sizeof(a[0]);
printf("Before sorting array elements are - \n");
print(a, n);
bubble(a, n);
printf("\nAfter sorting array elements are - \n");
print(a, n);
}

Output :
23811A4249

Footer 23
Program :
#include<stdio.h>
void print(int a[], int n) //function to print array elements
{
int i;
for(i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
}
void bubble(int a[], int n) // function to implement bubble sort
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void main ()
{
int i, j,temp;
int a[5] = { 10, 35, 32, 13, 26};
int n = sizeof(a)/sizeof(a[0]);
printf("Before sorting array elements are - \n");
print(a, n);
bubble(a, n);
printf("\nAfter sorting array elements are - \n");
print(a, n);
}

Output :
23811A4229

Footer 24
Selection sort :
The working procedure of selection sort is also simple. This article
will be very helpful and interesting to students as they might face selection sort
as a question in their examinations. So, it is important to discuss the topic.

In selection sort, the smallest value among the unsorted elements of the array is
selected in every pass and inserted to its appropriate position into the array. It is
also the simplest algorithm. It is an in-place comparison sorting algorithm. In
this algorithm, the array is divided into two parts, first is sorted part, and
another one is the unsorted part. Initially, the sorted part of the array is empty,
and unsorted part is the given array. Sorted part is placed at the left, while the
unsorted part is placed at the right.

In selection sort, the first smallest element is selected from the unsorted array
and placed at the first position. After that second smallest element is selected
and placed in the second position. The process continues until the array is
entirely sorted.

The average and worst-case complexity of selection sort is O(n2), where n is the
number of items. Due to this, it is not suitable for large data sets.

Selection sort is generally used when -

◦ A small array is to be sorted


◦ Swapping cost doesn't matter
◦ It is compulsory to check all elements

Algorithm :

SELECTION SORT(arr, n)

Step 1: Repeat Steps 2 and 3 for i = 0 to n-1


Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT

SMALLEST (arr, i, n, pos)


Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n

Footer 25
if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j
[END OF if]
[END OF LOOP]
Step 4: RETURN pos

Expected output :
Before sorting array elements are -
12 31 25 8 32 17
After sorting array elements are -
8 12 17 25 31 32

Working of Selection sort Algorithm :

Now, let's see the working of the Selection sort Algorithm.

To understand the working of the Selection sort algorithm, let's take an unsorted
array. It will be easier to understand the Selection sort via an example.

Let the elements of array are -

Now, for the first position in the sorted array, the entire array is to be scanned
sequentially.

At present, 12 is stored at the first position, after searching the entire array, it is
found that 8 is the smallest value.

So, swap 12 with 8. After the first iteration, 8 will appear at the first position in
the sorted array.

Footer 26
For the second position, where 29 is stored presently, we again sequentially scan
the rest of the items of unsorted array. After scanning, we find that 12 is the
second lowest element in the array that should be appeared at second position.

Now, swap 29 with 12. After the second iteration, 12 will appear at the second
position in the sorted array. So, after two iterations, the two smallest values are
placed at the beginning in a sorted way.

The same process is applied to the rest of the array elements. Now, we are
showing a pictorial representation of the entire sorting process.

Footer 27
Selection sort complexity :
Now, let's see the time complexity of selection sort in best case, average case,
and in worst case. We will also see the space complexity of the selection sort.

Time Complexity :

Best Case
O(n2)
Average Case
O(n2)
Worst Case
O(n2)
◦ Best Case Complexity - It occurs when there is no sorting required, i.e.
the array is already sorted. The best-case time complexity of selection
sort is O(n2).
◦ Average Case Complexity - It occurs when the array elements are in
jumbled order that is not properly ascending and not properly descending.
The average case time complexity of selection sort is O(n2).
◦ Worst Case Complexity - It occurs when the array elements are required
to be sorted in reverse order. That means suppose you have to sort the
array elements in ascending order, but its elements are in descending
order. The worst-case time complexity of selection sort is O(n2).

Space Complexity :
Space Complexity
O(1)
Stable
YES
◦ The space complexity of selection sort is O(1). It is because, in selection
sort, an extra variable is required for swapping.

Program :
#include <stdio.h>

void selection(int arr[], int n)


{
int i, j, small;

Footer 28
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array

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


if (arr[j] < arr[small])
small = j;
// Swap the minimum element with the first element
int temp = arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
selection(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

Output :
23811A4249

Footer 29
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array

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


if (arr[j] < arr[small])
small = j;
// Swap the minimum element with the first element
int temp = arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
selection(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

Output :
23811A4229

Footer 30
Insertion sort :
The working procedure of insertion sort is also simple. This article
will be very helpful and interesting to students as they might face insertion sort
as a question in their examinations. So, it is important to discuss the topic.

Insertion sort works similar to the sorting of playing cards in hands. It is


assumed that the first card is already sorted in the card game, and then we select
an unsorted card. If the selected unsorted card is greater than the first card, it
will be placed at the right side; otherwise, it will be placed at the left side.
Similarly, all unsorted cards are taken and put in their exact place.

The same approach is applied in insertion sort. The idea behind the insertion
sort is that first take one element, iterate it through the sorted array. Although it
is simple to use, it is not appropriate for large data sets as the time complexity
of insertion sort in the average case and worst case is O(n2), where n is the
number of items. Insertion sort is less efficient than the other sorting algorithms
like heap sort, quick sort, merge sort, etc.

Insertion sort has various advantages such as -

◦ Simple implementation
◦ Efficient for small data sets
◦ Adaptive, i.e., it is appropriate for data sets that are already
substantially sorted.

Algorithm :

Step 1 - If the element is the first element, assume that it is already sorted.
Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element,
then move to the next element. Else, shift greater elements in the array towards
the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

Footer 31
Working of Insertion sort Algorithm :

Now, let's see the working of the insertion sort Algorithm.

To understand the working of the insertion sort algorithm, let's take an unsorted
array. It will be easier to understand the insertion sort via an example.

Let the elements of array are -

Initially, the first two elements are compared in insertion sort.

Here, 31 is greater than 12. That means both elements are already in ascending
order. So, for now, 12 is stored in a sorted sub-array.

Now, move to the next two elements and compare them.

Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with
25. Along with swapping, insertion sort will also check it with all elements in
the sorted array.

For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12.
Hence, the sorted array remains sorted after swapping.

Footer 32
Now, two elements in the sorted array are 12 and 25. Move forward to the next
elements that are 31 and 8.

Both 31 and 8 are not sorted. So, swap them.

After swapping, elements 25 and 8 are unsorted.

So, swap them.

Now, elements 12 and 8 are unsorted.

So, swap them too.

Now, the sorted array has three items that are 8, 12 and 25. Move to the next
items that are 31 and 32.

Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.

Footer 33
Move to the next elements that are 32 and 17.

17 is smaller than 32. So, swap them.

Swapping makes 31 and 17 unsorted. So, swap them too.

Now, swapping makes 25 and 17 unsorted. So, perform swapping


again.

Now, the array is completely sorted.

Expected output:
Before sorting array elements are -

12 31 25 8 32 17

After sorting array elements are -

8 12 17 25 31 32

Insertion sort complexity:

Footer 34
Now, let's see the time complexity of insertion sort in best case, average case,
and in worst case. We will also see the space complexity of insertion sort.

Time Complexity:
Case Time Complexity
Best Case
O(n)
Average Case
O(n2)
Worst Case
O(n2)
◦ Best Case Complexity - It occurs when there is no sorting required, i.e.
the array is already sorted. The best-case time complexity of insertion sort
is O(n).
◦ Average Case Complexity - It occurs when the array elements are in
jumbled order that is not properly ascending and not properly descending.
The average case time complexity of insertion sort is O(n2).
◦ Worst Case Complexity - It occurs when the array elements are required
to be sorted in reverse order. That means suppose you have to sort the
array elements in ascending order, but its elements are in descending
order. The worst-case time complexity of insertion sort is O(n2).
Space Complexity:

Space Complexity
O(1)
Stable
YES
◦ The space complexity of insertion sort is O(1). It is because, in
insertion sort, an extra variable is required for swapping.

Program:
#include <stdio.h>

void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

Footer 35
while(j>=0 && temp <= a[j]) /
* Move the elements greater than temp to one position ahead from their current
position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output :
23811A4249

Footer 36
while(j>=0 && temp <= a[j]) /
* Move the elements greater than temp to one position ahead from their current
position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output :
23811A4229

Footer 37
WEEK - 2
List of experiments :
LinkedList Implementation

i) Implement a singly linked list and perform insertion and deletion operations.
ii) Develop a program to reverse a linked is iteratively and recursively.
iii) Solve problems involving linked list reversal and manipulation.

Footer 38
i) Implement a singly linked list and perform insertion and
deletion operations.

Singly-Linked List :
• A Singly-linked list can be defined as the collection of an ordered set of
elements.
• Nodes in the singly linked list consist of two parts such as the data part
and link part.
• The data part of the node stores actual information that is to be
represented by the node while the linked part of the node stores the
address of its immediate successor.
• In a single linked list, the address of the first node is always stored in a
reference node known as front. Sometimes it is also known as head
• Always the last node of the list contains a pointer to the null.
• In the Singly linked list data navigation happened in the forwarding
direction only.
• Basic operations supported by a list are insertion, deletion, display, and
search.
• Here we see Insertion and Deletion in detail.

Insertion Operation:
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.

Insertion at the beginning -


Steps to insert node at the beginning of singly linked list :

1. Create a new node, say newNode points to the newly created node.

Footer 39
2. Link the newly created node with the head node, i.e. the newNode will
now point to head node.

3. Make the new node as the head node, i.e. now head node will point to
newNode.

It involves inserting an element at the front of the list. It needs to make the new
node the head of the list.
Algorithm to insert node at the beginning of Singly Linked List
Being:
• Step 1 - Create a newNode with given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, set newNode→next = NULL and head =
newNode.
• Step 4 - If it is Not Empty then, set newNode→next = head and head =
newNode.

createSinglyLinkedList (head)
alloc (newNode)
If (newNode == NULL) then
write ('Unable to allocate memory')
End if
Else then
read (data)wo
newNode.data ← data

Footer 40
newNode.next ← head
head ← newNode
End else
End

Expected Output :
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 70
Enter the data of node 3: 23
Enter the data of node 4: 56
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 70
Data = 23
Data = 56

Enter data to insert at beginning of the list: 10


DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 10
Data = 70
Data = 23
Data = 56

Program :
/**
* C program to insert a new node at the beginning of a Singly Linked List
*/

#include <stdio.h>
#include <stdlib.h>

/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;

void createList(int n);


void insertNodeAtBeginning(int data);

Footer 41
void displayList();

int main()
{
int n, data;

/*
* Create a singly linked list of n nodes
*/
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();

/*
* Insert data at the beginning of the singly linked list
*/
printf("\nEnter data to insert at beginning of the list: ");
scanf("%d", &data);
insertNodeAtBeginning(data);

printf("\nData in the list \n");


displayList();

return 0;
}

/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;

head = (struct node *)malloc(sizeof(struct node));

/*
* If unable to allocate memory for head node
*/
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
/*
* Input data of node from the user
*/
printf("Enter the data of node 1: ");
scanf("%d", &data);

head->data = data; // Link data field with data


head->next = NULL; // Link address field to NULL

temp = head;

/*
* Create n nodes and adds to linked list

Footer 42
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

/* If memory is not allocated for newNode */


if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("Enter the data of node %d: ", i);
scanf("%d", &data);

newNode->data = data; // Link data field of newNode with data


newNode->next = NULL; // Link address field of newNode with NULL

temp->next = newNode; // Link previous node i.e. temp to the newNode

temp = temp->next;
}
}

printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}

/*
* Create a new node and inserts at the beginning of the linked list.
*/
void insertNodeAtBeginning(int data)
{
struct node *newNode;

newNode = (struct node*)malloc(sizeof(struct node));

if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; // Link data part
newNode->next = head; // Link address part

head = newNode; // Make newNode as first node

printf("DATA INSERTED SUCCESSFULLY\n");


}
}

/*
* Display entire list
*/
void displayList()
{
struct node *temp;

/*

Footer 43
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4249
Enter the total number of nodes: 4
Enter the data of node 1: 20
Enter the data of node 2: 30
Enter the data of node 3: 40
Enter the data of node 4: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 20
Data = 30
Data = 40
Data = 50

Enter data to insert at beginning of the list: 10


DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Footer 44
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4229
Enter the total number of nodes: 4
Enter the data of node 1: 20
Enter the data of node 2: 30
Enter the data of node 3: 40
Enter the data of node 4: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 20
Data = 30
Data = 40
Data = 50

Enter data to insert at beginning of the list: 10


DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Footer 45
Insertion at end of the list -
Insert node at the end of Singly Linked List :
Steps to insert a new node at the end of singly linked list.

Steps to insert node at the end of Singly linked list:


1. Create a new node and make sure that the address part of the new node
points to NULL i.e. newNode->next=NULL

2. Traverse to the last node of the linked list and connect the last node of the
list with the new node, i.e. last node will now point to new node.
(lastNode->next = newNode).

Algorithm to insert node at the end of Singly linked list: It involves insertion
at the last of the linked list. The new node can be inserted as the only node in
the list or it can be inserted as the last one. Different logics are implemented in
each scenario.

Footer 46
• Step 1 - Create a newNode with a given value and newNode → next as
NULL.
• Step 2 - Check whether list is Empty (head == NULL).
• Step 3 - If it is Empty then, set head = newNode.
• Step 4 - If it is Not Empty then, define a node pointer temp and initialize
with head.
• Step 5 - Keep moving the temp to its next node until it reaches the last
node in the list (until temp → next is equal to NULL).
• Step 6 - Set temp → next = newNode.
Begin:
createSinglyLinkedList (head)
alloc (newNode)
If (newNode == NULL) then
write ('Unable to allocate memory')
End if
Else then
read (data)
newNode.data ← data
newNode.next ← NULL
temp ← head
While (temp.next != NULL) do
temp ← temp.next
End while
temp.next ← newNode
End else
End

Expected output :
Enter the total number of nodes: 3
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30

Enter data to insert at end of the list: 40


DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Footer 47
Program :
/**
* C program to insert new node at the end of a Singly Linked List
*/

#include <stdio.h>
#include <stdlib.h>

/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;

void createList(int n);


void insertNodeAtEnd(int data);
void displayList();

int main()
{
int n, data;
/*
* Create a singly linked list of n nodes
*/
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();
/*
* Insert data at the end of the singly linked list
*/
printf("\nEnter data to insert at end of the list: ");
scanf("%d", &data);
insertNodeAtEnd(data);

printf("\nData in the list \n");


displayList();

return 0;
}

/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;

head = (struct node *)malloc(sizeof(struct node));

/*
* If unable to allocate memory for head node
*/
if(head == NULL)
{
printf("Unable to allocate memory.");
}

Footer 48
else
{
/*
* Reads data of node from the user
*/
printf("Enter the data of node 1: ");
scanf("%d", &data);

head->data = data; // Link the data field with data


head->next = NULL; // Link the address field to NULL

temp = head;

/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

/* If memory is not allocated for newNode */


if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("Enter the data of node %d: ", i);
scanf("%d", &data);

newNode->data = data; // Link the data field of newNode with data


newNode->next = NULL; // Link the address field of newNode with NULL

temp->next = newNode; // Link previous node i.e. temp to the newNode


temp = temp->next;
}
}

printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}

/*
* Create a new node and inserts at the end of the linked list.
*/
void insertNodeAtEnd(int data)
{
struct node *newNode, *temp;

newNode = (struct node*)malloc(sizeof(struct node));

if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; // Link the data part
newNode->next = NULL;

temp = head;

Footer 49
// Traverse to the last node
while(temp != NULL && temp->next != NULL)
temp = temp->next;

temp->next = newNode; // Link address part

printf("DATA INSERTED SUCCESSFULLY\n");


}
}

/*
* Display entire list
*/
void displayList()
{
struct node *temp;

/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4249
Enter the total number of nodes: 3
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30

Enter data to insert at end of the list: 40


DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Footer 50
// Traverse to the last node
while(temp != NULL && temp->next != NULL)
temp = temp->next;

temp->next = newNode; // Link address part

printf("DATA INSERTED SUCCESSFULLY\n");


}
}

/*
* Display entire list
*/
void displayList()
{
struct node *temp;

/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4229
Enter the total number of nodes: 3
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30

Enter data to insert at end of the list: 40


DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Footer 51
Insertion after the specified node -
It involves insertion after the specified node of the linked list. It needs to skip
the desired number of nodes to reach the node after which the new node will be
inserted.

Steps to insert node after the specified nodeof Singly Linked


List :

1. Create a new node.

2. Traverse to the n-1th position of the linked list and connect the new node with
the n+1th node. Means the new node should also point to the same node that the
n-1th node is pointing to. (newNode->next = temp->next where temp is the
n-1th node).

Footer 52
3. Now at last connect the n-1th node with the new node i.e. the n-1th node will
now point to new node. (temp->next = newNode where temp is n-1th node).

Algorithm :
• Step 1 - Create a newNode with the given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, set newNode → next = NULL and head =
newNode.
• Step 4 - If it is Not Empty then, define a node pointer temp and initialize
with head.
• Step 5 - Keep moving the temp to its next node until it reaches the node
after which we want to insert the newNode (until temp1 → data is equal
to location, here location is the node value after which we want to insert
the newNode).
• Step 6 - Every time check whether temp is reached to the last node or not.
If it is reached to the last node then display 'Given node is not found in
the list!!! Insertion not possible!!!' and terminate the function. Otherwise,
move the temp to the next node.
• Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp → next
= newNode’
%% Input : n position to insert data in the list
Begin:
createSinglyLinkedList (head)
alloc (newNode)
If (newNode == NULL) then
write ('Unable to allocate memory.')
End if
Else then
read (data)
newNode.data ← data
temp ← head
For i ← 2 to n-1
temp ← temp.next
If (temp == NULL) then
break
End if
End for
If (temp != NULL) then
newNode.next ← temp.next
temp.next ← newNode
End if

Footer 53
End else
End

Expected output :
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 40
Enter the data of node 4: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 40
Data = 50

Enter data to insert at middle of the list: 30


Enter the position to insert new node: 3
DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Output :
23811A4249
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 40
Enter the data of node 4: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 40
Data = 50

Footer 54
Enter data to insert at middle of the list: 30
Enter the position to insert new node: 3
DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Footer 55
End else
End

Expected output :
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 40
Enter the data of node 4: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 40
Data = 50

Enter data to insert at middle of the list: 30


Enter the position to insert new node: 3
DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Output :
23811A4229
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 40
Enter the data of node 4: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 40
Data = 50

Footer 56
Enter data to insert at middle of the list: 30
Enter the position to insert new node: 3
DATA INSERTED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Footer 57
Deletion Operation:
The Deletion of a node from a singly linked list can be performed at different
positions same as in insertion. Based on the position of the node being deleted,
the operation is categorized into the following categories.

Steps to delete first node from Singly Linked List:


1. Copy the address of first node i.e. head node to some temp variable say
toDelete.

2.

3. Move the head to the second node of the linked list i.e. head = head-
>next.

4. Disconnect the connection of first node to second node.

5. Free the memory occupied by the first node.

Footer 58
Deletion at the beginning -
It involves the deletion of a node from the beginning of the list. This is the
simplest operation of all. It just needs a few adjustments in the node pointers.
• Step 1 - Check whether the list is Empty (head == NULL)
• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminates the function.
• Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize
with head.
• Step 4 - Check whether the list is having only one node (temp → next ==
NULL)
• Step 5 - If it is TRUE then set head = NULL and delete temp (Setting
Empty list conditions)
• Step 6 - If it is FALSE then set head = temp → next, and delete temp.
%%Input: head of the linked list
Begin:
If (head != NULL) then
toDelete ← head
head ← head.next
unalloc (toDelete)
End if
End

Expected output:
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Press 1 to delete first node: 1

Data deleted = 10
SUCCESSFULLY DELETED FIRST NODE FROM LIST

Data in the list


Data = 20
Data = 30
Data = 40
Data = 50

Footer 59
Program :
/**
* C program to delete first node from Singly Linked List
*/

#include <stdio.h>
#include <stdlib.h>

/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;

void createList(int n);


void deleteFirstNode();
void displayList();

int main()
{
int n, choice;

/*
* Create a singly linked list of n nodes
*/
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();

printf("\nPress 1 to delete first node: ");


scanf("%d", &choice);

/* Delete first node from list */


if(choice == 1)
deleteFirstNode();

printf("\nData in the list \n");


displayList();

return 0;
}

/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;

head = (struct node *)malloc(sizeof(struct node));

/*
* If unable to allocate memory for head node

Footer 60
*/
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
/*
* In data of node from the user
*/
printf("Enter the data of node 1: ");
scanf("%d", &data);

head->data = data; // Link the data field with data


head->next = NULL; // Link the address field to NULL

temp = head;

/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

/* If memory is not allocated for newNode */


if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("Enter the data of node %d: ", i);
scanf("%d", &data);

newNode->data = data; // Link the data field of newNode with data


newNode->next = NULL; // Link the address field of newNode with NULL

temp->next = newNode; // Link previous node i.e. temp to the newNode


temp = temp->next;
}
}

printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}

/*
* Deletes the first node of the linked list
*/
void deleteFirstNode()
{
struct node *toDelete;

if(head == NULL)
{
printf("List is already empty.");
}
else
{
toDelete = head;

Footer 61
head = head->next;

printf("\nData deleted = %d\n", toDelete->data);

/* Clears the memory occupied by first node*/


free(toDelete);

printf("SUCCESSFULLY DELETED FIRST NODE FROM LIST\n");


}
}

/*
* Displays the entire list
*/
void displayList()
{
struct node *temp;
/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
}
Output :
23811A4249
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Press 1 to delete first node: 1

Data deleted = 10
SUCCESSFULLY DELETED FIRST NODE FROM LIST

Data in the list


Data = 20
Data = 30
Data = 40
Data = 50

Footer 62
head = head->next;

printf("\nData deleted = %d\n", toDelete->data);

/* Clears the memory occupied by first node*/


free(toDelete);

printf("SUCCESSFULLY DELETED FIRST NODE FROM LIST\n");


}
}

/*
* Displays the entire list
*/
void displayList()
{
struct node *temp;
/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
}
}
Output :
23811A4229
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Press 1 to delete first node: 1

Data deleted = 10
SUCCESSFULLY DELETED FIRST NODE FROM LIST

Data in the list


Data = 20
Data = 30
Data = 40
Data = 50

Footer 63
Deletion at the end of the list -
It involves deleting the last node of the list. The list can either be empty or full.
A different logic is implemented for the different scenarios.
Steps to delete last node of a Singly Linked List

1. Traverse to the last node of the linked list keeping track of the second last
node in some temp variable say secondLastNode.

2. If the last node is the head node then make the head node as NULL else
disconnect the second last node with the last node i.e. secondLastNode-
>next = NULL.

3. Free the memory occupied by the last node.

Algorithm :
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminates the function.
• Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2', and initialize 'temp1' with head.
• Step 4 - Check whether the list has only one Node (temp1 → next ==
NULL)
• Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And
terminate the function. (Setting Empty list condition)

Footer 64
• Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its
next node. Repeat the same until it reaches the last node in the list. (until
temp1 → next == NULL)
• Step 7 - Finally, Set temp2 → next = NULL and delete temp1.
Algorithm to delete last node of Singly Linked List
%%Input : head node of the linked list
Begin:
If (head == NULL) then
write ('List is already empty')
End if
Else then
toDelete ← head
secondLastNode ← head
While (toDelete.next != NULL) do
secondLastNode ← toDelete
toDelete ← toDelete.next
End while
If (toDelete == head) then
head ← NULL
End if
Else then
secondLastNode.next ← NULL
End else
unalloc (toDelete)
End else
End

Expected output:
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Press 1 to delete last node: 1


SUCCESSFULLY DELETED LAST NODE OF LIST

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Program :
/**
* C program to delete last node of Singly Linked List
*/

#include <stdio.h>

Footer 65
#include <stdlib.h>

/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;

void createList(int n);


void deleteLastNode();
void displayList();

int main()
{
int n, choice;

/*
* Create a singly linked list of n nodes
*/
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();

printf("\nPress 1 to delete last node: ");


scanf("%d", &choice);

/* Delete last node from list */


if(choice == 1)
deleteLastNode();

printf("\nData in the list \n");


displayList();

return 0;
}

/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;

head = (struct node *)malloc(sizeof(struct node));

/*
* If unable to allocate memory for head node
*/
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
/*
* Input data of node from the user

Footer 66
*/
printf("Enter the data of node 1: ");
scanf("%d", &data);

head->data = data; // Link the data field with data


head->next = NULL; // Link the address field to NULL

temp = head;

/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

/* If memory is not allocated for newNode */


if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("Enter the data of node %d: ", i);
scanf("%d", &data);

newNode->data = data; // Link the data field of newNode with data


newNode->next = NULL; // Link the address field of newNode with NULL

temp->next = newNode; // Link previous node i.e. temp to the newNode


temp = temp->next;
}
}

printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}

/*
* Delete last node of the linked list
*/
void deleteLastNode()
{
struct node *toDelete, *secondLastNode;

if(head == NULL)
{
printf("List is already empty.");
}
else
{
toDelete = head;
secondLastNode = head;

/* Traverse to the last node of the list */


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

Footer 67
if(toDelete == head)
{
head = NULL;
}
else
{
/* Disconnect link of second last node with last node */
secondLastNode->next = NULL;
}

/* Delete the last node */


free(toDelete);

printf("SUCCESSFULLY DELETED LAST NODE OF LIST\n");


}
}

/*
* Display entire list
*/
void displayList()
{
struct node *temp;

/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print the data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4249
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Press 1 to delete last node: 1

Footer 68
SUCCESSFULLY DELETED LAST NODE OF LIST

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Footer 69
if(toDelete == head)
{
head = NULL;
}
else
{
/* Disconnect link of second last node with last node */
secondLastNode->next = NULL;
}

/* Delete the last node */


free(toDelete);

printf("SUCCESSFULLY DELETED LAST NODE OF LIST\n");


}
}

/*
* Display entire list
*/
void displayList()
{
struct node *temp;

/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print the data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4229
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40
Data = 50

Press 1 to delete last node: 1

Footer 70
SUCCESSFULLY DELETED LAST NODE OF LIST

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Footer 71
Deletion after the specified node -
It involves deleting the node after the specified node in the list. It needs to skip
the desired number of nodes to reach the node after which the node will be
deleted. This requires traversing through the list.

Steps to delete middle node of Singly Linked List:

1. Traverse to the nth node of the singly linked list and also keep reference
of n-1th node in some temp variable say prevnode.

2. Reconnect the n-1th node with the n+1th node i.e. prevNode->next =
toDelete->next (Where prevNode is n-1th node and toDelete node is the
nth node and toDelete->next is the n+1th node).

3. Free the memory occupied by the nth node i.e. toDelete node.

Algorithm:
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminates the function.
• Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2', and initialize 'temp1' with head.

Footer 72
• Step 4 - Keep moving the temp1 until it reaches the exact node to be
deleted or to the last node. And every time set 'temp2 = temp1' before
moving the 'temp1' to its next node.
• Step 5 - If it is reached to the last node then display 'Given node not
found in the list! Deletion not possible!!!'. And terminate the function.
• Step 6 - If it is reached to the exact node which we want to delete, then
check whether the list is having only one node or not
• Step 7 - If the list has only one node and that is the node to be deleted,
then set head = NULL and delete temp1 (free(temp1)).
• Step 8 - If the list contains multiple nodes, then check whether temp1 is
the first node in the list (temp1 == head).
• Step 9 - If temp1 is the first node then move the head to the next node
(head = head → next) and delete temp1.
• Step 10 - If temp1 is not the first node then check whether it is the last
node in the list (temp1 → next == NULL).
• Step 11 - If temp1 is last node then set temp2 → next = NULL and delete
temp1 (free(temp1)).
• Step 12 - If temp1 is not first node and not last node then set temp2 →
next = temp1 → next and delete temp1 (free(temp1))
%%Input : head node of the linked list
n node to be deleted
Begin:
If (head == NULL) then
write ('List is already empty')
End if
Else then
toDelete ← head
prevNode ← head
For i←2 to n do
prevNode ← toDelete
toDelete ← toDelete.next
If (toDelete == NULL) then
break
End if
End for
If (toDelete != NULL) then
If (toDelete == head) then
head ← head.next
End if
prevNode.next ← toDelete.next
toDelete.next ← NULL
unalloc (toDelete)
End if
End else
End

Expected output :
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
SINGLY LINKED LIST CREATED SUCCESSFULLY

Footer 73
Data in the list
Data = 10
Data = 20
Data = 30
Data = 40

Enter the node position you want to delete: 3


SUCCESSFULLY DELETED NODE FROM MIDDLE OF LIST

Data in the list


Data = 10
Data = 20
Data = 40

Program :
/**
* C program to delete middle node of Singly Linked List
*/

#include <stdio.h>
#include <stdlib.h>

/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
} *head;

/* Functions used in program */


void createList(int n);
void deleteMiddleNode(int position);
void displayList();

int main()
{
int n, position;

/*
* Create a singly linked list of n nodes
*/
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);

printf("\nData in the list \n");


displayList();

printf("\nEnter the node position you want to delete: ");


scanf("%d", &position);

/* Delete middle node from list */


deleteMiddleNode(position);

printf("\nData in the list \n");


displayList();

return 0;
}

Footer 74
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;

head = (struct node *)malloc(sizeof(struct node));

/*
* If unable to allocate memory for head node
*/
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
/*
* Read data of node from the user
*/
printf("Enter the data of node 1: ");
scanf("%d", &data);

head->data = data; // Link the data field with data


head->next = NULL; // Link the address field to NULL

temp = head;

/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

/* If memory is not allocated for newNode */


if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("Enter the data of node %d: ", i);
scanf("%d", &data);

newNode->data = data; // Link the data field of newNode with data


newNode->next = NULL; // Link the address field of newNode with NULL

temp->next = newNode; // Link previous node i.e. temp to the newNode


temp = temp->next;
}
}

printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}

Footer 75
/*
* Delete middle node of the linked list
*/
void deleteMiddleNode(int position)
{
int i;
struct node *toDelete, *prevNode;

if(head == NULL)
{
printf("List is already empty.");
}
else
{
toDelete = head;
prevNode = head;

for(i=2; i<=position; i++)


{
prevNode = toDelete;
toDelete = toDelete->next;

if(toDelete == NULL)
break;
}

if(toDelete != NULL)
{
if(toDelete == head)
head = head->next;

prevNode->next = toDelete->next;
toDelete->next = NULL;

/* Delete nth node */


free(toDelete);

printf("SUCCESSFULLY DELETED NODE FROM MIDDLE OF LIST\n");


}
else
{
printf("Invalid position unable to delete.");
}
}
}

/*
* Display entire list
*/
void displayList()
{
struct node *temp;

/*
* If the list is empty i.e. head = NULL
*/
if(head == NULL)
{
printf("List is empty.");
}
else

Footer 76
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print the data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4249
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Enter the node position you want to delete: 3


SUCCESSFULLY DELETED NODE FROM MIDDLE OF LIST

Data in the list


Data = 10
Data = 20
Data = 40

Footer 77
{
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print the data of current node
temp = temp->next; // Move to next node
}
}
}

Output :
23811A4229
Enter the total number of nodes: 4
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
SINGLY LINKED LIST CREATED SUCCESSFULLY

Data in the list


Data = 10
Data = 20
Data = 30
Data = 40

Enter the node position you want to delete: 3


SUCCESSFULLY DELETED NODE FROM MIDDLE OF LIST

Data in the list


Data = 10
Data = 20
Data = 40

Footer 78
ii) Develop a program to reverse a linked is iteratively and
recursively.

Iterative:
The main concept of the iterative approach is to use the
three different pointers. These pointers will point to the particular nodes on
every iteration and change the address of the nodes.

Algorithm:
Step 1: Take three pointers and initialize them as prev = NULL, next = NULL
and curr = head.
Step 2: Iterate through the end of the list and follow the next steps.
Step 3: Store the address of the next node in the next pointer.
Step 4: Update the curr next to the prev pointer.
Step 5: Update the next pointer by curr pointer.
Step 6: Move the curr pointer to the next node.

Program Explanation
1. Creating some nodes with data and appending them at the start of the linked
list.
2. Print the list before reversing the original list.
3. Take three pointers to update the node’s address.
4. Iterate through the list from start to end node.
5. On every iteration, store the next node of the current node.
6. Point the current node to its previous node.
7. Move the previous and current pointers to their next node.
8. In the end, Update the head pointer to the start node of the reversed list.
9. Print the reversed list.

Expected output:

Linked List before reversed:


99 → 78 → 31 → 90 → 10 → NULL

Linked List after reversed:


10 → 90 → 31 → 78 → 99 → NULL

Footer 79
Time Complexity: O(n)
Since the size of the list is n, where is the number of nodes. The traversing of
the list is from the start node to the end node which is the size of the list.

Space Complexity: O(1)


There are only three pointers used to reverse the list which is a constant space
and it is not depending on the size of the list.

Program :

/*
* C Program to Reverse a Linked List using three pointer
*/
#include<stdio.h>
#include<malloc.h>
/*
* A linked list node
*/
struct node
{
int data;
struct node* next;
};
//Globally initialized head pointer
struct node* head = NULL;

//function prototyping
struct node*create_node(int);
void insert_begin(int);
void reverse_list();
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
reverse_list();
printf("\nLinked List after reversed: \n");

Footer 80
print();
return 0;
}

/*
* Creates a new node using the malloc function
*/
struct node* create_node(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}

/*
* insert a new node at the beginning of the list
*/
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}

/*
* reverse the linked list
*/
void reverse_list()
{
struct node* prev = NULL, *curr = head, *next = NULL;
while (curr != NULL)
{
// store the next node
next = curr -> next;

Footer 81
// reverse the pointer of the current node
curr ->next = prev;
// move prev pointer to the current node
prev = curr;
// move current to its next node
curr = next;
}
//update the head pointer by prev pointer
head = prev;
}

/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d → ", temp->data);
temp = temp->next;
}
printf("NULL \n");
}

Program:

23811A4249

Linked List before reversed:


99 78 31 90 10 NULL

Linked List after reversed:


10 90 31 78 99 NULL

Footer 82










// reverse the pointer of the current node
curr ->next = prev;
// move prev pointer to the current node
prev = curr;
// move current to its next node
curr = next;
}
//update the head pointer by prev pointer
head = prev;
}

/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d → ", temp->data);
temp = temp->next;
}
printf("NULL \n");
}

Program:

23811A4229

Linked List before reversed:


99 78 31 90 10 NULL

Linked List after reversed:


10 90 31 78 99 NULL

Footer 83










Recursion:
In this method, it uses recursive function & reverses the nodes in a linked list
and displays the list. A linked list is an ordered set of data elements, each
containing a link to its successor. This program makes each data element to link
to its predecessor.

Algorithm:

Step 1: Take three pointers and initialize them as prev = NULL, next = NULL
and curr = head.
Step 2: Iterate through the end of the list and follow the next steps.
Step 3: Store the address of the next node in the next pointer.
Step 4: Update the curr next to the prev pointer.
Step 5: Update the next pointer by curr pointer.
Step 6: Move the curr pointer to the next node.

Expected output:

LinkedList : 4 3 2 1
LinkedList in reverse order : 1 2 3 4

Time Complexity: O(n)


The function is calling itself n times, which is the size of the linked list.

Space Complexity: O(n)


The maximum size of the function call is n, which stores each node of the
list on every call onto the stack.

Program:

/*
* Recursive C program to reverse nodes of a linked list and display
* them
*/
#include <stdio.h>
#include <stdlib.h>

Footer 84
struct node
{
int data;
struct node *next;
};

void print_reverse_recursive (struct node *);


void print (struct node *);
void create_new_node (struct node *, int );

//Driver Function
int main ()
{
struct node *head = NULL;
insert_new_node (&head, 1);
insert_new_node (&head, 2);
insert_new_node (&head, 3);
insert_new_node (&head, 4);
printf ("LinkedList : ");
print (head);
printf ("\nLinkedList in reverse order : ");
print_reverse_recursive (head);
printf ("\n");
return 0;
}

//Recursive Reverse
void print_reverse_recursive (struct node *head)
{
if (head == NULL)
{
return;
}

//Recursive call first


print_reverse_recursive (head -> next);
//Print later
printf ("%d ", head -> data);
}

//Print the linkedlist normal


void print (struct node *head)
{
if (head == NULL)
{

Footer 85
return;
}
printf ("%d ", head -> data);
print (head -> next);
}

//New data added in the start


void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}

Output:

23811A4249

LinkedList : 4 3 2 1
LinkedList in reverse order : 1 2 3 4

Footer 86
return;
}
printf ("%d ", head -> data);
print (head -> next);
}

//New data added in the start


void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}

Output:

23811A4229

LinkedList : 4 3 2 1
LinkedList in reverse order : 1 2 3 4

Footer 87
iii) Solve problems involving linked list reversal and manipulation.

Reversal:
Reverse Linked List is a linked list created to form a linked list by
inverting the links within the list. The first node in the linked list is the last
node in the linked list, and the last node is the first node.

Expected output:
Linked List before reversed:
1 → 2 → 3 → 4 → 5 → NULL

Reversed Linked List:


5 → 4 → 3 → 2 → 1 → NULL

Problem Solution:
To solve this problem, we need to follow the given steps:

1. Given the head pointer of the linked list.


2. Reverse the order of the linked list by updating the pointer of the node.
3. Update the head of the list.
4. Print the linked list before and after reversing it.
5. Exit.

Program Explanation:
1. Creating some nodes with data and appending them at the start of the linked
list.
2. Print the list before reversing the original list.
3. Iterate through the list from start to end node.
4. On every iteration, create a new node and store the data of the current
iterating node.
5. Insert this node at the beginning of the list.
6. In the end, Update the head pointer to the new head pointer.
7. Print the reversed list.

Time Complexity: O(n)


Since the size of the list is n, where is the number of nodes. The traversing of
the list is from the start node to the end node which is the size of the list.

Footer 88
Space Complexity: O(n)
Another list of the same size is created so the space complexity becomes the
factor of n, which is the size of the list.

Program:
/*
* C Program to Reverse a Linked List using iterative
*/
#include<stdio.h>
#include<malloc.h>
/*
* A linked list node
*/
struct node
{
int data;
struct node* next;
};

//Globally initialized head pointer


struct node* head = NULL;

//function prototyping
struct node* create_node(int);
void insert_begin(int);
void reverse_list();
void print();
int main()
{
/* Create some nodes and insert data into them */
insert_begin(10);
insert_begin(90);
insert_begin(31);
insert_begin(78);
insert_begin(99);
printf("Linked List before reversed: \n");
print();
reverse_list();
printf("\nLinked List after reversed: \n");
print();
return 0;
}

/*
* Creates a new node using the malloc function
*/
struct node* create_node(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));
if (new_node == NULL)
{
printf("Memory can't be allocated for new node");
return NULL;

Footer 89
}
else
{
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
}

/*
* insert a new node at the beginning of the list
*/
void insert_begin(int data)
{
struct node* new_node = create_node(data);
if (new_node != NULL)
{
new_node -> next = head;
head = new_node;
}
}

/*
* reverse the linked list
*/
void reverse_list()
{
if (head == NULL)
{
return;
}
struct node* temp = head;
struct node* new_head = NULL;

// create new nodes and insert them beginning


while (temp != NULL)
{
struct node* new_node = create_node(temp->data);
new_node->next = new_head;
new_head = new_node;
temp = temp->next;
}

// update the head with the new head


head = new_head;
}

/*
* prints the linked list
*/
void print()
{
struct node* temp = head;
while (temp != NULL)
{
printf("%d --> ", temp->data);
temp = temp->next;
}

Footer 90
printf("NULL \n");
}

Output:
23811A4249
Linked List before reversed:
99 78 31 90 10 NULL

Linked List after reversed:


10 90 31 78 99 NULL

Footer 91










printf("NULL \n");
}

Output:
23811A4229
Linked List before reversed:
99 78 31 90 10 NULL

Linked List after reversed:


10 90 31 78 99 NULL

Footer 92










Linked list manipulation:-
Expeceted output:-
Original linked list: 1 2 3 4 5

Reversed linked list: 5 4 3 2 1

Algorithm:-
• Initialize three pointers: prev, current, and next.

• Set prev to NULL, current to the head of the linked list, and next to
NULL.

• Traverse the linked list:

• Set next to the next node of current.

• Set the next pointer of current to prev.

• Move prev to current and current to next.

• Set the head of the linked list to prev, which is now pointing to the last
node.

Program:
#include <stdio.h>

#include <stdlib.h>

struct Node {
int data;
struct Node* next; };
struct Node* reverseLinkedList(struct Node* head) {

struct Node* prev = NULL;


struct Node* current = head;

Footer 93
struct Node* next = NULL;
while (current != NULL) {

next = current->next;

current->next = prev;

prev = current;

current = next;

return prev;

void printLinkedList(struct Node* head) {

struct Node* temp = head;


while (temp != NULL) {

printf("%d ", temp->data);

temp = temp->next; }

printf("\n"); }

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;

}
int main() {

printf("23811A4237\n");

struct Node* head = createNode(1);

head->next = createNode(2);
head->next->next = createNode(3);

head->next->next->next = createNode(4);

Footer 94
head->next->next->next->next = createNode(5);

printf("Original linked list: “);

printLinkedList(head);
head = reverseLinkedList(head);

printf("Reversed linked list: “);

printLinkedList(head);

Output:

Footer 95

You might also like