Program in C to remove duplicates node from a unsorted linked list
//Remove duplicates elements from a unordered linked list #include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; void insert(struct Node **head, int data){ struct Node *newN, *temp; newN = malloc(sizeof(struct Node)); newN->data = data; newN->next = NULL; if(*head == NULL) *head = newN; else { temp = *head; while(temp->next != 0) temp = temp->next; temp->next = newN; } } void show(struct Node **head){ struct Node *temp; temp = *head; if(*head == 0) printf("Linked list empty..."); else{ while(temp != 0){ printf("%5d",temp->data); temp = temp->next; } } } void removeDuplicate(struct Node **head){ struct Node *temp = NULL, *prev = NULL, *temp1 = NULL; temp = *head; while(temp->next != NULL){ temp1 = temp; while(temp1->next != NULL){ prev = temp1; temp1 = temp1->next; if(temp1->data == temp->data){ prev->next = temp1->next; free(temp1); temp1 = prev; if(temp1->next == 0) //if it is the last Node then next has NULL value; break; } } temp = temp->next; } } int main(){ struct Node *head = NULL; insert(&head, 90); insert(&head, 15); insert(&head, 55); insert(&head, 25); insert(&head, 55); insert(&head, 55); insert(&head, 15); printf("\nElements are :"); show(&head); removeDuplicate(&head); printf("\nAfter remove elements are :"); show(&head); return 0; }
Output :-
0 Comments