LeetCode 82. Remove Duplicates from Sorted List II(删除排序链表中的重复元素 II)--c语言

82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:

Input: 1->1->1->2->3
Output: 2->3

解题思路:

/*
执行用时 : 20 ms, 在Remove Duplicates from Sorted List II的C提交中击败了29.95% 的用户
内存消耗 : 7.6 MB, 在Remove Duplicates from Sorted List II的C提交中击败了38.30% 的用户
*/
/**
 * 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;
    }
    struct ListNode* L = (struct ListNode*)malloc(sizeof(struct ListNode));
    L->next = head;
    struct ListNode* p = head->next;//工作指针,遍历链表
    struct ListNode* pre = head;//pre指向某数值第一次出现时的结点
    struct ListNode* tail = L;//指向需返回结点的尾节点,用于收集需返回的结点
    
    while(p != NULL){
        if(p->val == pre->val){
            //由于是有序的,所以先找出一个不与前面结点值相等的结点
            while(p != NULL && p->val == pre->val){
                p = p->next;
            }
            tail->next = p;//删除重复元素,注意,此时并没用释放结点,只是简单地断开了链接
            pre = p;//指向新的数值,此数值第一次出现
            if(p){//由于前面的while,所以需重新判断p为不为空
                p = p->next;
            }
        }
        else{
            //代表pre结点不是重复元素,链接到返回链表区
            //此时pre指向的结点值是第一次出现,p为其后继,tail为其前驱
            
            p = p->next;
            pre = pre->next;
            tail = tail->next;
        }
    }
    return L->next;
}
/*
对于原链表的尾结点。当它与它的前驱相等时,程序执行if条件,p指向它的next,此时为NULL,再tail = p;当它与前驱不相等时,程序执行else,p指向它的next,为NULL,tail指向其前驱,pre指向p(即尾节点),此时tail与最后一个结点未断开,最后一个结点也加入了返回链表区
*/
/*
最后执行的输入:
[1,1]
*/

 

LeetCode 83. Remove Duplicates from Sorted List(删除排序链表中的重复元素) -- c语言

https://blog.csdn.net/d_benhua/article/details/90712146

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值