Complementary task for topic: 11
M Nemeth · 2023-08-29 15:21:04.634218'
Linked list: delete element
Linked list: delete element
Write a program to delete a node with a given value from a singly linked list (integer).
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 delete a node with a given value from the linked list
void deleteNode(struct Node** head, int value) {
if (*head == NULL) {
printf("Linked list is empty. Nothing to delete.\n");
return;
}
struct Node* current = *head;
struct Node* prev = NULL;
// Traverse the list to find the node with the given value
while (current != NULL && current->data != value) {
prev = current;
current = current->next;
}
// If the node with the given value is found, delete it
if (current != NULL) {
if (prev != NULL) {
prev->next = current->next;
} else {
*head = current->next;
}
free(current);
printf("Node with value %d deleted from the linked list.\n", value);
} else {
printf("Node with value %d not found in the linked list.\n", value);
}
}
int main() {
struct Node* head = NULL;
addToFront(&head, 3);
addToFront(&head, 2);
addToFront(&head, 1);
printf("Original linked list: ");
printList(head);
deleteNode(&head, 2);
deleteNode(&head, 4);
printf("Linked list after deleting nodes: ");
printList(head);
return 0;
}