Final answer:
This answer provides example programs and explanations for counting nodes in a linked list, calculating the average of a linked list of real numbers, inserting a new node after the Nth node, and deleting the Nth node in a linked list.
Step-by-step explanation:
To count the nodes in a linked list, you can traverse the list starting from the head node and increment a counter variable until the last node is reached. Here is an example program:
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
int countNodes(struct Node* first) {
int count = 0;
struct Node* current = first;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
For the average of a linked list of real numbers, you can iterate through the list, summing up the numbers and counting the nodes. Then, divide the sum by the number of nodes to get the average. Here's an example:
float calculateAverage(struct Node* first) {
float sum = 0;
int count = 0;
struct Node* current = first;
while (current != NULL) {
sum += current->data;
count++;
current = current->next;
}
if (count != 0) {
return sum / count;
} else {
return 0;
}
}
To insert a new node after the Nth node in a linked list, you need to iterate to the Nth node and change the next pointers accordingly. Here's an example:
void insertAfterN(struct Node* first, int N, int data) {
struct Node* current = first;
for (int i = 0; i < N; i++) {
if (current == NULL) {
return;
}
current = current->next;
}
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = current->next;
current->next = newNode;
}
To delete the Nth node in a linked list, you need to iterate to the (N-1)th node and change the next pointer to skip the Nth node. Here's an example:
void deleteNth(struct Node* first, int N) {
struct Node* current = first;
if (N == 0) {
first = first->next;
free(current);
return;
}
for (int i = 0; i < N-1; i++) {
if (current == NULL || current->next == NULL) {
return;
}
current = current->next;
}
struct Node* toBeDeleted = current->next;
current->next = toBeDeleted->next;
free(toBeDeleted);
}