c语言怎么删除链表中的重复元素

   2025-02-05 7520
核心提示:要删除链表中的重复元素,可以使用双重循环遍历链表,对于每个节点,再遍历其后续节点,如果有与当前节点值相同的节点,则删除该

要删除链表中的重复元素,可以使用双重循环遍历链表,对于每个节点,再遍历其后续节点,如果有与当前节点值相同的节点,则删除该节点。

具体实现如下:

#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;}

运行结果:

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

注意:在删除节点时应释放内存,防止内存泄漏。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言