#include <stdio.h>
#include <stdlib.h>
/
* Node structure for a singly linked list.
*/
typedef struct Node {
int data;
struct Node* next;
} Node;
/
* Function to create a new node with the given data.
*/
Node* createNode(int data) {
Node newNode = (Node)malloc(sizeof(Node));
if (newNode == NULL) {
perror("Error creating a new node");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
/
* Function to insert a new node at the beginning of the linked list.
*/
void insertAtBeginning(Node head, int data) {
Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
/
* Function to print the elements of the linked list.
*/
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
/
* Function to delete the first occurrence of a node with the given data.
*/
void deleteNode(Node head, int data) {
if (*head == NULL) {
fprintf(stderr, "List is empty, cannot delete\n");
return;
}
Node current = head;
Node* prev = NULL;
while (current != NULL && current->data != data) {
prev = current;
current = current->next;
}
if (current == NULL) {
fprintf(stderr, "Data not found in the list\n");
return;
}
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
}
/
* Function to free the memory occupied by the linked list.
*/
void freeList(Node head) {
Node current = head;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*head = NULL;
}
int main() {
Node* head = NULL;
insertAtBeginning(&head, 3);
insertAtBeginning(&head, 7);
insertAtBeginning(&head, 1);
insertAtBeginning(&head, 9);
printf("Linked List: ");
printList(head);
deleteNode(&head, 1);
printf("After deleting 1: ");
printList(head);
deleteNode(&head, 7);
printf("After deleting 7: ");
printList(head);
freeList(&head);
return 0;
}