Untitled
#include <stdio.h> #include <stdlib.h> // Node structure for the linked list 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 of the linked list struct Node* insertAtBeginning(struct Node* head, int data) { struct Node* newNode = createNode(data); newNode->next = head; return newNode; } // Function to insert a new node at the end of the linked list struct Node* insertAtEnd(struct Node* head, int data) { struct Node* newNode = createNode(data); if (head == NULL) { return newNode; } struct Node* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; return head; } // Function to delete a node with a specific value from the linked list struct Node* deleteNode(struct Node* head, int value) { if (head == NULL) { return NULL; } if (head->data == value) { struct Node* temp = head; head = head->next; free(temp); return head; } struct Node* current = head; while (current->next != NULL && current->next->data != value) { current = current->next; } if (current->next == NULL) { // Node with the given value not found return head; } struct Node* temp = current->next; current->next = current->next->next; free(temp); return head; } // Function to search for a node with a specific value in the linked list struct Node* searchNode(struct Node* head, int value) { struct Node* current = head; while (current != NULL && current->data != value) { current = current->next; } return current; } // Function to display the linked list void displayList(struct Node* head) { struct Node* temp = head; printf("Linked List: "); while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } // Main function to test operations on linear linked list int main() { struct Node* head = NULL; // Inserting elements at the beginning head = insertAtBeginning(head, 30); head = insertAtBeginning(head, 20); head = insertAtBeginning(head, 10); // Displaying the linked list displayList(head); // Inserting elements at the end head = insertAtEnd(head, 40); head = insertAtEnd(head, 50); // Displaying the linked list after insertion at the end displayList(head); // Deleting a node with value 30 head = deleteNode(head, 30); // Displaying the linked list after deletion displayList(head); // Searching for a node with value 20 struct Node* searchResult = searchNode(head, 20); if (searchResult != NULL) { printf("Node with value 20 found.\n"); } else { printf("Node with value 20 not found.\n"); } return 0; } /* Linked List: 10 20 30 Linked List: 10 20 30 40 50 Linked List: 10 20 40 50 Node with value 20 found. */
Leave a Comment