Program to remove duplicates from a linked list

August 29th, 2009  |  Published in Amit Sahrawat, Data Structures, Linux Sample Programs








/* Structure for a linked list*/
struct list{
    int num;
    struct list* next; /* pointer to next node in list*/
};

#define FREE(x) free(x);x=NULL;
/* Function to remove duplicates from a linked list, given the head pointer for the list*/
void removeDuplicates(struct list** head)
{
    struct list* temp = NULL;
    struct list* dup = NULL;
    printf(“[%s]\n”,__FUNCTION__);
    temp = *head;
    while(temp->next != NULL)
    {
        if(temp->num == temp->next->num)
        {
            dup = temp->next;
            if(temp->next)
                temp->next = temp->next->next;
            else
                temp->next = NULL;
            FREE(dup);
            temp = *head;
            continue;
        }
        temp = temp->next;
    }
}
/* Function to use the linked list functions*/
int main()
{
    struct list* node = NULL;
    insert(&node,2);
    insert(&node,2);
    insert(&node,5);
    insert(&node,5);
    insert(&node,5);
    insert(&node,7);
    insert(&node,8);
    insert(&node,8);
    insert(&node,9);
    insert(&node,9);
    removeDuplicates(&node);
    traverse(node);
}

Subscribe

Get articles in your inbox.

Enter your email address:

Join Us

Twitter Chatter


Recommendations

Archives

Categories