Untitled
unknown
plain_text
a month ago
16 kB
4
Indexable
#include <stdio.h> #include <stdlib.h> // Node structure definition 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)); if (!newNode) { printf("Memory allocation failed!\n"); exit(1); } newNode->data = data; newNode->next = NULL; return newNode; } // Function to insert a node at the end void insertAtEnd(struct Node** head, int data) { struct Node* newNode = createNode(data); if (*head == NULL) { *head = newNode; return; } struct Node* temp = *head; while (temp->next != NULL) temp = temp->next; temp->next = newNode; } // Function to insert a node at the beginning void insertAtBeginning(struct Node** head, int data) { struct Node* newNode = createNode(data); newNode->next = *head; *head = newNode; } // Function to delete a node with a given key void deleteNode(struct Node** head, int key) { struct Node* temp = *head, *prev = NULL; // If head node itself holds the key if (temp != NULL && temp->data == key) { *head = temp->next; free(temp); return; } // Search for the key while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // Key not found if (temp == NULL) { printf("Node with value %d not found!\n", key); return; } // Unlink the node and free memory prev->next = temp->next; free(temp); } // Function to search for a node int search(struct Node* head, int key) { struct Node* temp = head; while (temp != NULL) { if (temp->data == key) return 1; // Found temp = temp->next; } return 0; // Not found } // Function to display the linked list void display(struct Node* head) { struct Node* temp = head; if (head == NULL) { printf("List is empty!\n"); return; } while (temp != NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); } // Main function to demonstrate linked list operations int main() { struct Node* head = NULL; int choice, value, key; while (1) { printf("\nMenu:\n"); printf("1. Insert at Beginning\n"); printf("2. Insert at End\n"); printf("3. Delete Node\n"); printf("4. Search Node\n"); printf("5. Display List\n"); printf("6. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: printf("Enter value to insert at beginning: "); scanf("%d", &value); insertAtBeginning(&head, value); break; case 2: printf("Enter value to insert at end: "); scanf("%d", &value); insertAtEnd(&head, value); break; case 3: printf("Enter value to delete: "); scanf("%d", &key); deleteNode(&head, key); break; case 4: printf("Enter value to search: "); scanf("%d", &key); printf("Search result: %s\n", search(head, key) ? "Found" : "Not Found"); break; case 5: printf("Linked List: "); display(head); break; case 6: printf("Exiting program...\n"); exit(0); break; default: printf("Invalid choice! Please enter a valid option.\n"); } } return 0; } } } } } } } } } } } } } } } } } } }
Editor is loading...
Leave a Comment