w3resource

C Exercises: Remove duplicates from a sorted singly linked list

C Singly Linked List : Exercise-35 with Solution

Write a C program to remove duplicates from a sorted singly 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;
}

// Function to remove duplicates in a sorted node
void remove_Duplicates(struct Node* head) {
    if (head == NULL) {
        return;
    }
    struct Node* curr = head;
    while (curr->next != NULL) {
        if (curr->data == curr->next->data) {
            struct Node* temp = curr->next;
            curr->next = curr->next->next;
            free(temp);
        } else {
            curr = curr->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* head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(3);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = newNode(6);
    head->next->next->next->next->next ->next = newNode(6);
    printf("Original sorted singly linked list:\n");
	displayList(head);
	printf("\nAfter removing duplicates from the said sorted linked list:\n");
	remove_Duplicates(head);
	displayList(head);
    return 0;
}

Sample Output:

Original sorted singly linked list:
1 2 3 3 5 6 6 

After removing duplicates from the said sorted linked list:
1 2 3 5 6   

Flowchart :

Flowchart: Remove duplicates from a sorted singly linked list.
Flowchart: Remove duplicates from a sorted singly linked list.

C Programming Code Editor:

Previous: Merge alternate nodes of two linked lists.
Next: Reverse a singly linked list in blocks of size k.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.