Data Structures 1st and 2nd Week
Data Structures 1st and 2nd Week
LIST OF EXPERIMENTS :
Array Manipulation:
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>
printf("\n");
}
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.
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).
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 :
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 :
Footer 12
Expected output:
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.
◦ Iterative method.
◦ Recursive method.
The recursive method of binary search follows the divide and conquer approach.
We have to use the below formula to calculate the mid of the array -
beg = 0
end = 8
Footer 13
Now, the element to search is found. So algorithm will return the index of the
element matched
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.
Algorithm :
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 :
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).
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.
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 -
Second Pass :
Footer 20
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array
will be -
Third Pass :
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array
will be -
Fourth pass :
Footer 21
Similarly, after the fourth iteration, the array will be -
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
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.
Algorithm :
SELECTION SORT(arr, 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
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.
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>
Footer 28
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array
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
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.
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.
◦ 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.
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.
Footer 31
Working of 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.
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.
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.
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.
Expected output:
Before sorting array elements are -
12 31 25 8 32 17
8 12 17 25 31 32
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;
}
}
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;
}
}
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.
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
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;
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);
/*
* 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);
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
/*
* 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);
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));
temp = temp->next;
}
}
/*
* Create a new node and inserts at the beginning of the linked list.
*/
void insertNodeAtBeginning(int data)
{
struct node *newNode;
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; // Link data part
newNode->next = head; // Link address part
/*
* 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
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
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.
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
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;
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);
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
/*
* 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);
temp = head;
/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
/*
* Create a new node and inserts at the end of the linked list.
*/
void insertNodeAtEnd(int data)
{
struct node *newNode, *temp;
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;
/*
* 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
Footer 50
// Traverse to the last node
while(temp != NULL && temp->next != NULL)
temp = temp->next;
/*
* 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
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.
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
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
Footer 54
Enter data to insert at middle of the list: 30
Enter the position to insert new node: 3
DATA INSERTED SUCCESSFULLY
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
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
Footer 56
Enter data to insert at middle of the list: 30
Enter the position to insert new node: 3
DATA INSERTED SUCCESSFULLY
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.
2.
3. Move the head to the second node of the linked list i.e. head = head-
>next.
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 deleted = 10
SUCCESSFULLY DELETED FIRST NODE FROM LIST
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;
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);
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
/*
* 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);
temp = head;
/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
/*
* 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;
/*
* 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 deleted = 10
SUCCESSFULLY DELETED FIRST NODE FROM LIST
Footer 62
head = head->next;
/*
* 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 deleted = 10
SUCCESSFULLY DELETED FIRST NODE FROM LIST
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.
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
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;
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);
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
/*
* 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);
temp = head;
/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
/*
* 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;
Footer 67
if(toDelete == head)
{
head = NULL;
}
else
{
/* Disconnect link of second last node with last node */
secondLastNode->next = NULL;
}
/*
* 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
Footer 68
SUCCESSFULLY DELETED LAST NODE OF LIST
Footer 69
if(toDelete == head)
{
head = NULL;
}
else
{
/* Disconnect link of second last node with last node */
secondLastNode->next = NULL;
}
/*
* 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
Footer 70
SUCCESSFULLY DELETED LAST NODE OF LIST
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.
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
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;
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);
return 0;
}
Footer 74
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
/*
* 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);
temp = head;
/*
* Create n nodes and adds to linked list
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
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;
if(toDelete == NULL)
break;
}
if(toDelete != NULL)
{
if(toDelete == head)
head = head->next;
prevNode->next = toDelete->next;
toDelete->next = NULL;
/*
* 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
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
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:
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.
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
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
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
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;
};
//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;
}
Footer 85
return;
}
printf ("%d ", head -> data);
print (head -> next);
}
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);
}
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
Problem Solution:
To solve this problem, we need to follow the given steps:
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.
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;
};
//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;
/*
* 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
Footer 91
→
→
→
→
→
→
→
→
→
→
printf("NULL \n");
}
Output:
23811A4229
Linked List before reversed:
99 78 31 90 10 NULL
Footer 92
→
→
→
→
→
→
→
→
→
→
Linked list manipulation:-
Expeceted output:-
Original linked list: 1 2 3 4 5
Algorithm:-
• Initialize three pointers: prev, current, and next.
• Set prev to NULL, current to the head of the linked list, and next to
NULL.
• 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) {
Footer 93
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
return prev;
temp = temp->next; }
printf("\n"); }
}
int main() {
printf("23811A4237\n");
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
Footer 94
head->next->next->next->next = createNode(5);
printLinkedList(head);
head = reverseLinkedList(head);
printLinkedList(head);
Output:
Footer 95