|
| 1 | +// A complete working C program to demonstrate deletion in singly |
| 2 | +// linked list gien the key to delete |
| 3 | +#include <stdio.h> |
| 4 | +#include <stdlib.h> |
| 5 | + |
| 6 | +// A linked list node |
| 7 | +struct Node |
| 8 | +{ |
| 9 | + int data; |
| 10 | + struct Node *next; |
| 11 | +}; |
| 12 | + |
| 13 | +/* Given a reference (pointer to pointer) to the head of a list |
| 14 | + and an int, inserts a new node on the front of the list. */ |
| 15 | +void push(struct Node** head_ref, int new_data) |
| 16 | +{ |
| 17 | + struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); |
| 18 | + new_node->data = new_data; |
| 19 | + new_node->next = (*head_ref); |
| 20 | + (*head_ref) = new_node; |
| 21 | +} |
| 22 | + |
| 23 | +/* Given a reference (pointer to pointer) to the head of a list |
| 24 | + and a key, deletes the first occurrence of key in linked list */ |
| 25 | +void deleteNode(struct Node **head_ref, int key) |
| 26 | +{ |
| 27 | + // Store head node |
| 28 | + struct Node* temp = *head_ref, *prev; |
| 29 | + |
| 30 | + // If head node itself holds the key to be deleted |
| 31 | + if (temp != NULL && temp->data == key) |
| 32 | + { |
| 33 | + *head_ref = temp->next; // Changed head |
| 34 | + free(temp); // free old head |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + // Search for the key to be deleted, keep track of the |
| 39 | + // previous node as we need to change 'prev->next' |
| 40 | + while (temp != NULL && temp->data != key) |
| 41 | + { |
| 42 | + prev = temp; |
| 43 | + temp = temp->next; |
| 44 | + } |
| 45 | + |
| 46 | + // If key was not present in linked list |
| 47 | + if (temp == NULL) return; |
| 48 | + |
| 49 | + // Unlink the node from linked list |
| 50 | + prev->next = temp->next; |
| 51 | + |
| 52 | + free(temp); // Free memory |
| 53 | +} |
| 54 | + |
| 55 | +// This function prints contents of linked list starting from |
| 56 | +// the given node |
| 57 | +void printList(struct Node *node) |
| 58 | +{ |
| 59 | + while (node != NULL) |
| 60 | + { |
| 61 | + printf(" %d ", node->data); |
| 62 | + node = node->next; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/* Drier program to test above functions*/ |
| 67 | +int main() |
| 68 | +{ |
| 69 | + /* Start with the empty list */ |
| 70 | + struct Node* head = NULL; |
| 71 | + |
| 72 | + push(&head, 7); |
| 73 | + push(&head, 1); |
| 74 | + push(&head, 3); |
| 75 | + push(&head, 2); |
| 76 | + |
| 77 | + puts("Created Linked List: "); |
| 78 | + printList(head); |
| 79 | + deleteNode(&head, 1); |
| 80 | + puts("\nLinked List after Deletion of 1: "); |
| 81 | + printList(head); |
| 82 | + return 0; |
| 83 | +} |
0 commit comments