Complementary task for topic: 11
M Nemeth · 2023-08-29 15:21:04.634218'
Linked list: Destroy list
Linked list: Destroy list
Extend the previous task by adding a function to delete the entire linked list and free the memory used by each node
Hint: Drawing always help to figure out what to do!
Solution
#include
#include
// Define the structure for a node in the singly linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node with the given data
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to add a new node at the front of the linked list
void addToFront(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to print the elements of the linked list
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// Function to reverse the linked list
void reverseList(struct Node** head) {
struct Node* prev = NULL;
struct Node* current = *head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
// Function to destroy the entire linked list and free memory
void destroyList(struct Node** head) {
struct Node* current = *head;
struct Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*head = NULL; // Set head to NULL to indicate the list is now empty
}
int main() {
struct Node* head = NULL;
addToFront(&head, 3);
addToFront(&head, 2);
addToFront(&head, 1);
printf("Original linked list: ");
printList(head);
reverseList(&head);
printf("Reversed linked list: ");
printList(head);
destroyList(&head);
printf("Linked list after destroying: ");
printList(head); // This will print an empty list since the memory has been deallocated
return 0;
}