链表删除重复元素,怎么改


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* deleteDuplicates(struct ListNode* head){

    

    struct ListNode* current=head;    

    while(current->next){

        if(current->val=current->next->val){

            current->next=current->next->next;

            free(current->next);

        }

    else{
        current=current->next;
        }
    }

    return current->next;

}

供参考:

#include <stdio.h>
#include <stdlib.h>
struct ListNode {
    int   val;
    struct ListNode* next;
};

struct ListNode* RemoveDuplicates(struct ListNode* head)
{
    struct ListNode* p = head->next, * preq, * q;
    while (p != NULL)
    {
        preq = p;
        q = p->next;
        while (q) {
            if (q->val == p->val) {
                preq->next = q->next;
                free(q);
                q = preq->next;
            }
            else {
                preq = q;
                q = q->next;
            }
        }
        p = p->next;
    }
    return head;
}

利用双重循环吧

https://blog.csdn.net/Fizz6018/article/details/106816783/

【以下回答由 GPT 生成】

对于上述代码的优化,主要包括以下几个方面:

  1. 处理特殊情况:如果链表为空或者只有一个节点,直接返回原链表。
  2. 修复内存释放问题:在删除重复节点时,需要先释放掉重复节点的内存,再将当前节点的next指针指向下一个非重复节点。
  3. 返回修改后的链表首节点:在代码中使用current->next作为返回值,这是不正确的,应该返回链表的头节点head。

下面是优化后的代码:

struct ListNode* deleteDuplicates(struct ListNode* head){
    // 处理特殊情况
    if(head == NULL || head->next == NULL){
        return head;
    }

    struct ListNode* current = head;

    // 循环遍历链表
    while(current->next){
        // 如果有重复节点
        if(current->val == current->next->val){
            struct ListNode* temp = current->next;
            current->next = current->next->next;
            free(temp);
        }
        else{
            current = current->next;
        }
    }

    return head;
}

请注意,这里假设原始链表是有序的,如果链表无序,则需要先对链表进行排序再进行删除重复节点的操作。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^