Sure, here's a simple implementation of a singly linked list in C with insert, delete, add, and search functions:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a new node at the beginning
void insert(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to delete a node with the given key
void delete(struct Node** head, int key) {
struct Node* temp = *head, *prev;
if (temp != NULL && temp->data == key) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
// Function to add a new node at the end
void add(struct Node** head, int data) {
struct Node* newNode = createNode(data);
struct Node* last = *head;
if (*head == NULL) {
*head = newNode;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// Function to search for a node
struct Node* search(struct Node* head, int key) {
struct Node* current = head;
while (current != NULL) {
if (current->data == key) {
return current;
}
current = current->next;
}
return NULL;
}
// Function to print the list
void printList(struct Node* node) {
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
add(&head, 1);
add(&head, 2);
add(&head, 3);
insert(&head, 0);
printList(head); // Output: 0 -> 1 -> 2 -> 3 -> NULL
delete(&head, 1);
printList(head); // Output: 0 -> 2 -> 3 -> NULL
struct Node* foundNode = search(head, 2);
if (foundNode != NULL) {
printf("Node with key 2 found: %d\n", foundNode->data);
} else {
printf("Node with key 2 not found\n");
}
return 0;
}
This code defines a simple struct Node to represent the linked list nodes and provides functions to insert, delete, add, and search nodes in the list. The main function demonstrates how to use these functions to create and manipulate the linked list.