Write a program to delete a node at Nth position from Linked List. Given a linked list, we have to write a method to delete a node from Nth position.
Program to delete a complete linked list
Program to Delete a Node at Nth Position from Linked List
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 94 95 96 97 98 99 100 |
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; }; //Global declaration of head pointer struct node* head; // Insert function insert a node at the beginning of a linked list void insert(int data) { struct node* newNode; newNode = (struct node*)malloc(sizeof(struct node*)); newNode->data = data; newNode->next = head; head = newNode; } void deleteNode(int position) { struct node* temp; // Pointer p points to head struct node* p = head; int count = 0; // If linked list is empty if (p == NULL) { printf(" Linked list is empty "); return; } // If first element of linked list is deleted if (position == 0) { head = p->next; free(p); } else { while (count < position-1 && p != NULL) { p = p->next; } temp = p->next; p->next = temp->next; free(temp); head = p; } } void print(){ struct node* p; p = head; while(p != NULL) { printf( "%d\n", p->data); p = p->next; } printf("\n"); } int main(void) { head = NULL; insert(3); insert(7); insert(8); insert(9); printf("After insertion of linked list\n"); print(); // Delete a node from first position deleteNode(1); printf("After deletion of linked list from a given position \n"); print(); return 0; } |
Output : –
1 2 3 4 5 6 7 8 9 10 |
After insertion of linked list 9 8 7 3 After deletion of linked list from a given position 9 7 3 |