In this program, we are going to share a C program to delete N nodes after M nodes of a linked list. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to delete N nodes after M nodes of a linked list with the output.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void push(struct Node ** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print linked list */ void printList(struct Node *head) { struct Node *temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } void skipMdeleteN(struct Node *head, int M, int N) { struct Node *curr = head, *t; int count; while (curr) { // Skip M nodes for (count = 1; count<M && curr!= NULL; count++) curr = curr->next; // If we reached end of list, then return if (curr == NULL) return; // Start from next node and delete N nodes t = curr->next; for (count = 1; count<=N && t!= NULL; count++) { struct node *temp = t; t = t->next; free(temp); } curr->next = t; // Link the previous list with remaining nodes // Set current pointer for next iteration curr = t; } } int main() { /* Create following linked list 1->2->3->4->5->6->7->8->9->10 */ struct Node* head = NULL; int M=2, N=3; push(&head, 10); push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf("M = %d, N = %d \nGiven Linked list is :\n", M, N); printList(head); skipMdeleteN(head, M, N); printf("\nLinked list after deletion is :\n"); printList(head); return 0; } |
M = 2, N = 3
Given Linked list is :
1 2 3 4 5 6 7 8 9 10
Linked list after deletion is :
1 2 6 7
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.