“How to remove duplicate elements from a linked list in C language?”

To remove duplicate elements in a linked list, you can use a nested loop to iterate through the list. For each node, iterate through its subsequent nodes and delete any nodes with the same value as the current node.

The specific implementation is as follows:

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

// 定义链表节点
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 创建链表
Node* createList(int* arr, int size) {
    if (size == 0) {
        return NULL;
    }
    Node* head = (Node*)malloc(sizeof(Node));
    head->data = arr[0];
    head->next = NULL;
    Node* p = head;
    int i;
    for (i = 1; i < size; i++) {
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = arr[i];
        newNode->next = NULL;
        p->next = newNode;
        p = p->next;
    }
    return head;
}

// 打印链表
void printList(Node* head) {
    Node* p = head;
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

// 删除链表中的重复元素
void removeDuplicates(Node* head) {
    Node* p = head;
    while (p != NULL) {
        Node* q = p;
        while (q->next != NULL) {
            if (q->next->data == p->data) {
                Node* temp = q->next;
                q->next = q->next->next;
                free(temp);
            } else {
                q = q->next;
            }
        }
        p = p->next;
    }
}

int main() {
    int arr[] = {1, 2, 3, 2, 4, 1, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    Node* head = createList(arr, size);
    printf("原始链表:");
    printList(head);
    removeDuplicates(head);
    printf("删除重复元素后的链表:");
    printList(head);
    return 0;
}

Result of execution:

原始链表:1 2 3 2 4 1 5 
删除重复元素后的链表:1 2 3 4 5 

Warning: memory should be released when deleting nodes to prevent memory leaks.

bannerAds