w3resource

C Exercises: Remove duplicates from a unsorted singly linked list

C Singly Linked List : Exercise-16 with Solution

Write a C program to remove duplicates from a single unsorted linked list.

Sample Solution:

C Code:

#include<stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* newNode(int data) {
    struct Node* node = (struct Node*) malloc(sizeof(struct Node));
    node->data = data;
    node->next = NULL;
    return node;
}

void remove_Duplicates(struct Node* head) {
    struct Node *current = head, *next_next;

    // Check each node of the linked list
    while (current->next != NULL) {
        // Check if the current node's value is equal to the next node's value
        if (current->data == current->next->data) {
            next_next = current->next->next;
            free(current->next);
            current->next = next_next;
        } else {
            current = current->next;
        }
    }
}

// Function to print a linked list
void displayList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
	struct Node* head1 = newNode(1);
    head1->next = newNode(2);
    head1->next->next = newNode(3);
    head1->next->next->next = newNode(3);
    head1->next->next->next->next = newNode(4);
    printf("Original Singly List:\n");
	displayList(head1);
	printf("After removing duplicate elements from the said singly list:\n");
	remove_Duplicates(head1);
    displayList(head1);
    struct Node* head2 = newNode(1);
    head2->next = newNode(2);
    head2->next->next = newNode(3);
    head2->next->next->next = newNode(3);
    head2->next->next->next->next = newNode(4);
    head2->next->next->next->next->next = newNode(4);
    printf("\nOriginal Singly List:\n");
	displayList(head2);
	printf("After removing duplicate elements from the said singly list:\n");
	remove_Duplicates(head2);
    displayList(head2);
    return 0;
}

Sample Output:

Original Singly List:
1 2 3 3 4 
After removing duplicate elements from the said singly list:
1 2 3 4 

Original Singly List:
1 2 3 3 4 4 
After removing duplicate elements from the said singly list:
1 2 3 4 

Flowchart :

Flowchart: Remove duplicates from a unsorted singly linked list.

C Programming Code Editor:

Previous: Check if a singly linked list is palindrome or not.
Next: Sort a singly linked list using merge sort.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.