I've written the function for removing duplicate elements in a doubly linked circular list. However when traversing the list after removing, I am not getting the desired output.
I have used typedef to enclose
#define MAX 10
typedef struct node {
int data;
struct node *next, *prev;
} NODE;
NODE *rem(NODE *head) {
NODE *node = head;
int hash[MAX] = { 0 };
while (node != NULL) {
hash[node->data]++;
node = node->next;
}
node = head;
NODE *node2 = head->next;
while (node2 != NULL) {
if (hash[node2->data] != 1) {
NODE *r = node2;
node->next = node2->next;
node2->next->prev = node;
free(r);
hash[node->data]--;
}
node = node2;
node2 = node2->next;
}
return head;
}
Using the debugger shows segmentation fault in line:
hash[node->data]++;
I have created a hash array to keep count of duplicate elements and keep removing the elements until the count of each element is 1.
But traversing the list after the function does not give any output.
There are multiple problems in your code:
datamember of all nodes must be inthe range0toMAX-1. You should at least verify this to avoid writing outside the arrayhash. The nameMAXsuggest the array should have a length ofMAX + 1, but testing the actual values is a useful precaution.nextmember is incorrect: you should test if the current node has circled back to theheadof the list instead.Here is a modified version that works for both circular and null terminated lists: