Search code examples
cstructlinked-listsingly-linked-listfunction-definition

Singly linked list, A small problem in main function


Wrote this program to delete Node with same data in a sorted linked list, but the while loop is not executing as expected . By using some printf statements, I figured out while loop was executed once ,but statements after first if condition is not executed. Can you please reply me why this is happening ,and how can I solve this?

Note : Insert and Print function are user defined functions.

Insert(&Head,char data): it inserts data at the begining of linked list every time it is called;

void Insert(struct Node **Head, char data)
{
    struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = *Head;
    *Head = temp;
}

Print :it takes head of List and prints the linked list in output terminal.

void Print(struct Node *Head)
{
    printf("%c", Head->data);
    while (Head->next != NULL)
    {
        Head = Head->next;
        printf("\t%c", Head->data);
    } 
}

...

int main()
{
    struct Node *Head = NULL;
    Insert(&Head, '6');
    Insert(&Head, '5');
    Insert(&Head, '5');
    Insert(&Head, '5');
    Insert(&Head, '5');
    Insert(&Head, '5');
    Insert(&Head, '5');
    Insert(&Head, '4');
    Insert(&Head, '4');
    Insert(&Head, '3');
    Insert(&Head, '2');
    Insert(&Head, '1');
    Insert(&Head, '1');
    Insert(&Head, '1');

    printf("dta---%c\n", Head->data);
    Print(Head);

    //Code to deleate duplicate data  from a sorted singly linked list
    struct Node *PreviousHead = NULL;
    while (Head != NULL)
    {
        if (PreviousHead->data == Head->data) //i think there is some error in this statement...
        {
            while (PreviousHead->data == Head->data)
            {
                
                PreviousHead->next = Head->next;
                free(Head);
                Head = PreviousHead->next;
                if (Head == NULL)
                    break;
            }
        }
        
        PreviousHead = Head;
        Head = Head->next;

        if (PreviousHead->data == Head->data)
        {
            PreviousHead->next = Head->next;
            free(Head);
            Head = PreviousHead->next;
        }
    }
    Print(Head);
}

Solution

  • Try this for deleting duplicates from a singly linked list. You have a lot of issues with NULL checking and unnecessary code.

    while (Head != NULL)
    {
        struct Node *next = Head->next;
    
        while (next != NULL && Head->data == next->data) {
            Head->next = next->next;
            free(next)
            next = Head->next;
        }
    
        Head = Head->next;
    }