I am executing a program for removing duplicates from an unsorted linked list using two loops.
The program includes two structs for defining Node and newNode. Also, it includes two user-defined functions removeDuplicates for removing duplicates of linked-list and printList for printing the list.
struct Node {
       int data;
       struct Node *next;
};
struct Node *newNode(int data) {
       Node *temp = new Node;
       temp->data = data;
       temp->next = NULL;
       return temp;
};
/* Function to remove duplicates from an unsorted linked list */
void removeDuplicates(struct Node *start) {
     struct Node *ptr1, *ptr2, *dup;
     ptr1 = start;
     while (ptr1 != NULL && ptr1->next != NULL) {
           ptr2 = ptr1;
           while (ptr2->next != NULL) {
                 if (ptr1->data == ptr2->next->data) {
                    dup = ptr2->next;
                    ptr2->next = ptr2->next->next;
                    delete (dup);
                 } else
                    ptr2 = ptr2->next;
                 ptr1 = ptr1->next;
           }
     }
}
void printList(struct Node *node) {
     while (node != NULL) {
           printf("%d  ", node->data);
           node = node->next;
     }
     printf("\n");
}
I ran a couple of test cases,
case 1 Input : 12->11->12->21->41->43->21
   Output(from the program) : 12->11->12->21->41->43->21
       Required Output : 12->11->21->41->43
int main() {
    struct Node *start = newNode(12);
    start->next = newNode(11);
    start->next->next = newNode(12);
    start->next->next->next = newNode(21);
    start->next->next->next->next = newNode(41);
    start->next->next->next->next->next = newNode(43);
    start->next->next->next->next->next->next = newNode(21);
    printf("Linked List before removing duplicates");
    printList(start);
    removeDuplicates(start);
    printf("Linked List after removing duplicates");
    printList(start);
}
case 2 Input : 10->12->11->11->12->11->10
       Output : 10->12->11
int main() {
    struct Node *start = newNode(10);
    start->next = newNode(12);
    start->next->next = newNode(11);
    start->next->next->next = newNode(11);
    start->next->next->next->next = newNode(12);
    start->next->next->next->next->next = newNode(11);
    start->next->next->next->next->next->next = newNode(10);
    printf("Linked List before removing duplicates");
    printList(start);
    removeDuplicates(start);
    printf("Linked List after removing duplicates");
    printList(start);
}
The program works for one test case and not other case. What am I missing in the code?
 
     
     
     
    