LeetCode 83&&83. 删除排序链表中的重复元素 | C语言版

LeetCode 83. 删除排序链表中的重复元素

题目描述

题目地址83. 删除排序链表中的重复元素
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
在这里插入图片描述

解题思路

思路一:使用双指针
代码实现
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* deleteDuplicates(struct ListNode* head){
   //使用双指针
    if(head==NULL || head->next==NULL){
        return head;
    }

    //cur初始化为头节点
    struct ListNode* cur=head;
    //next初始化为NULL
    struct ListNode* next=NULL;

    while(cur!=NULL){
        //next为头节点的下一个节点
        next=cur->next;
        while(next!=NULL){
            if(cur->val==next->val){
                //如果两指针(相邻)指向的节点相等,则将cur的指针域指向next的的下一个节点
                cur->next=next->next;
            }
            next=next->next;
        }
        cur=cur->next;
    }
    return head;
}
运行结果

在这里插入图片描述

参考文章:

https://leetcode.cn/problems/remove-duplicates-from-sorted-list/solutions/342300/83-shan-chu-pai-xu-lian-biao-zhong-de-zhong-fu-21/?orderBy=hot&languageTags=c%2Ccpp

思路二:减少遍历节点数
代码实现
在这里插入代码片
运行结果
参考文章:

LeetCode 82. 删除排序链表中的重复元素 II

题目描述

题目地址82. 删除排序链表中的重复元素 II
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
在这里插入图片描述

解题思路

思路一:使用三指针
代码实现
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* deleteDuplicates(struct ListNode* head){
    //使用双指针
    if(head==NULL || head->next==NULL){
        return head;
    }

    //设置虚拟节点,指向head(减少边界判断)
    struct ListNode* dummyHead=(struct ListNode*)malloc(sizeof(struct ListNode));
    dummyHead->next=head;
    //last保存重复节点段的最后一个节点
    struct ListNode* last=dummyHead;
    //pre保存当前节点cur的前驱节点
    struct ListNode* pre=dummyHead;
    //当前节点cur
    struct ListNode* cur=pre->next;

    //dummyHead(pre)->head(cur)->...

    while(cur!=NULL){
        if(pre->val!=cur->val && (cur->next==NULL || cur->val!=cur->next->val)){
            last->next=cur;
            last=last->next;
        }

        //pre=pre->next;
        pre=cur;
        cur=cur->next;
    }
    last->next=NULL;
    return dummyHead->next;
}
运行结果

在这里插入图片描述

参考文章:

https://leetcode.cn/problems/remove-duplicates-from-sorted-list/solutions/342300/83-shan-chu-pai-xu-lian-biao-zhong-de-zhong-fu-21/?orderBy=hot&languageTags=c%2Ccpp

思路二:减少遍历节点数
代码实现
在这里插入代码片
运行结果
参考文章:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李莲花*

多谢多谢,来自一名大学生的感谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值