#include <stdio.h>
#include <stdlib.h>
// Define the structure of a node
typedef struct Node {
int data;
struct Node *next;
} Node;
// Function to create a new list node
Node* createNode(int data) {
Node
*newNode
= (Node
*)malloc(sizeof(Node
)); if (newNode == NULL) {
printf("Memory allocation failed.\n"); }
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to add a new node at the end of the list
Node* createList(Node *head, int data) {
Node *newNode = createNode(data);
if (head == NULL) {
return newNode;
}
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
return head;
}
// Function to search for a value in the list
Node* searchList(Node *head, int value) {
Node *current = head;
while (current != NULL) {
if (current->data == value) {
return current;
}
current = current->next;
}
return NULL;
}
// Function to insert a value at a specific position
Node* insertList(Node *head, int data, int position) {
Node *newNode = createNode(data);
if (position == 0) {
newNode->next = head;
return newNode;
}
Node *current = head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("Position out of bounds.\n"); return head;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
// Function to delete a node with a specific value
Node* deleteList(Node *head, int value) {
if (head == NULL) {
return NULL;
}
if (head->data == value) {
Node *temp = head;
head = head->next;
return head;
}
Node *current = head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next == NULL) {
return head;
}
Node *temp = current->next;
current->next = temp->next;
return head;
}
// Function to display the list
void displayList(Node *head) {
if (head == NULL) {
return;
}
Node *current = head;
while (current != NULL) {
printf("%d -> ", current
->data
); current = current->next;
}
}
// Function to free the entire list
void freeList(Node *head) {
Node *current = head;
while (current != NULL) {
Node *temp = current;
current = current->next;
}
printf("List has been freed.\n"); }
// Main function to test the list operations
int main() {
Node *head = NULL;
// Create list
head = createList(head, 10);
head = createList(head, 20);
head = createList(head, 30);
displayList(head);
// Search list
int searchValue = 20;
Node *foundNode = searchList(head, searchValue);
if (foundNode != NULL) {
printf("Value %d found in the list.\n", searchValue
); } else {
printf("Value %d not found in the list.\n", searchValue
); }
// Insert into list
head = insertList(head, 25, 2);
displayList(head);
// Delete from list
head = deleteList(head, 20);
displayList(head);
// Free the list
freeList(head);
head = NULL; // Set the head to NULL after freeing
displayList(head);
return 0;
}