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

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
在这里插入图片描述

思路

定义一个fast节点,一个cur节点,两个节点同时从head出发,val相同时,cur不动,fast向后走,直到与cur的val不相同,定义一个prev前驱节点保存cur的前一个节点;然后删除prev与fast之间的所有节点,然后继续迭代;

附上代码:

struct ListNode* deleteDuplicates(struct ListNode* head)
{
    
    
    //如果链表为空或只有一个结点,直接返回头结点
    if(head==NULL)
    return head;
    if(head->next==NULL)
    return head;
    
    struct ListNode* fast=head->next;
    struct ListNode* cur=head;
    struct ListNode* slow=NULL;

    while(fast)
    {
    
    
        //如果fast与cur的val不相等,三个节点同时向后走
        if(fast->val!=cur->val)
        {
    
    
            slow=cur;
            cur=fast;
            fast=fast->next;
        }
        //fast与cur的val相等
        else
        {
    
    
            //如果fast与cur的val相等,fast往后走,直至与cur的val不相等;
            while(fast&&cur->val==fast->val)
            {
    
    
                fast=fast->next;
            }
            //如果头两个节点的val就相等,删除fast之前的节点,将fast置为新的头;
            if(slow==NULL)
            {
    
    
                head=fast;
            }
            //删除slow与fast中间的节点
            else
            {
    
    
                slow->next=fast;
            }
            cur=fast;
            //如果未到NULL,继续迭代
            if(cur)
                fast=fast->next;
        }
    }
    return head;
}

猜你喜欢

转载自blog.csdn.net/qq_43745617/article/details/113076862