1. #include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
// Linked list structure
struct LinkedList {
struct Node* head;
};
// 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;
}
// Insertion at the beginning of the linked list
void insertAtBeginning(struct LinkedList* list, int data) {
struct Node* newNode = createNode(data);
newNode->next = list->head;
list->head = newNode;
}
// Insertion at the end of the linked list
void insertAtEnd(struct LinkedList* list, int data) {
2. struct Node* newNode = createNode(data);
if (list->head == NULL) {
list->head = newNode;
return;
}
struct Node* temp = list->head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Deletion of a node with a specific value
void deleteNode(struct LinkedList* list, int key) {
struct Node *temp = list->head, *prev = NULL;
if (temp != NULL && temp->data == key) {
list->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);
}
// Searching for a node with a specific value
int search(struct LinkedList* list, int key) {
3. struct Node* current = list->head;
while (current != NULL) {
if (current->data == key) {
return 1; // Found
}
current = current->next;
}
return 0; // Not found
}
// Display the linked list
void display(struct LinkedList* list) {
struct Node* temp = list->head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("n");
}
// Main function
int main() {
struct LinkedList linkedList;
linkedList.head = NULL;
// Inserting elements
insertAtBeginning(&linkedList, 3);
insertAtBeginning(&linkedList, 1);
insertAtEnd(&linkedList, 5);
// Displaying the linked list
4. printf("Linked List: ");
display(&linkedList);
// Deleting a node
deleteNode(&linkedList, 3);
printf("After deleting node with value 3: ");
display(&linkedList);
// Searching for a node
int keyToSearch = 5;
if (search(&linkedList, keyToSearch)) {
printf("Node with value %d is present.n", keyToSearch);
} else {
printf("Node with value %d is not present.n", keyToSearch);
}
return 0;
}
This C code defines a linked list structure containing a Node structure. It provides functions for
creating nodes, insertion at the beginning and end, deletion of a node with a specific value,
searching for a node, and displaying the linked list. The main function demonstrates how to use
these functions to manipulate the linked list.