Question: # : Write a function to deleteDuplicate that will take a pointer pointing to the head of a singly linked list of integers as argument and remove all the duplicate values (values that occur multiple times) from it. For example:
Example:
Sample Input: Initial Linked List: 2->3->5->5->8->3->6
Sample Output: Linked List after calling deleteDuplicate : 2->8->6
Solution:
#include<stdio.h>
struct node{
int val;
struct node *next;
}*head;
//create node;
void create(int n){
struct node *curr,*tail;
for(int i=0;i<n;i++){
curr = (struct node*)malloc(sizeof(struct node));
scanf("%d",&curr->val);
curr->next = NULL;
if(head == NULL){
head = curr;
tail = curr;
}
else{
tail->next = curr;
tail = curr;
}
}
}
//display node;
void display(){
struct node *tamp;
tamp = head;
while(tamp != NULL){
printf("%d\t",tamp->val);
tamp = tamp->next;
}
}
//delete any douplcate value;
void delete_any_douplcate_value(){
struct node *temp, *temp1, *dup;
int *p;
int c=0;
temp = head;
p = (int*)malloc(2*sizeof(int));
while(temp!=NULL && temp->next!=NULL){
temp1 = temp;
while(temp1->next!=NULL){
if(temp->val == temp1->next->val){
*(p+c) = temp->val;
dup = temp1->next;
temp1->next = temp1->next->next;
free(dup);
c++;
}
else{
temp1 = temp1->next;
}
}
temp = temp->next;
}
delete_a_particular_node(p);
printf("\nAll duplicate item has been deleted....\n");
}
void delete_a_particular_node(int *p){
struct node *temp,*temp1;
for(int i=0;i<2;i++){
int key = *(p+i);
printf("\n");
if(head!=NULL) {
temp = head;
if(temp -> next != NULL && temp -> val != key) {
temp1 = temp;
temp = temp->next;
}
if (temp -> val == key){
temp1 -> next = temp -> next;
free(temp);
} else{
printf("Search key not found\n");
}
}
}}
int main(){
int n;
printf("How many value you want to input: ");
scanf("%d",&n);
create(n);
display();
printf("\n");
delete_any_douplcate_value();
printf("\n");
display();
}
After Run:
How many value you want to input: 7
2 3 5 5 8 3 6
2 3 5 5 8 3 6
All duplicate item has been deleted....
2 8 6
Process returned 0 (0x0) execution time : 23.524 s
Press any key to continue.