题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

C语言

struct ListNode* deleteDuplicates(struct ListNode* head ) {

    // write code here

    struct ListNode* dummyHead = (struct ListNode*)malloc(sizeof(struct ListNode));

    struct ListNode* pre, *cur, *next;

    dummyHead->next = head;

    pre = dummyHead, cur = head, next = head->next;

    if(!cur || !next) return head;

    while(next){                            //如果next节点没到末尾,继续循环            dummy(p)-1(c)-1(n)-2-2-NULL

        if(cur->val != next->val){          //如果cur与next的值相等,三个指针一起移动   dummy(p)-1(c)-1(n)-2-2-NULL

            pre = cur;                      

            cur = next;

            next = next->next;

        }else{                              //如果cur与next的值不相等  

            while(next->next && next->val == next->next->val)   //将next移到最后一个    dummy(p)-1(c)-1(n)-2-2-NULL

                next = next->next;

            if(!next->next){                //如果next的下一个为空即 dummy(p)-1(c)-1(n)-NULL

                pre->next = NULL;           //dummy(p)-NULL

                return dummyHead->next;

            }

            cur = next->next;               //如果next的下一个不为空,                  dummy(p)-1   -1(c/n)-2-2-NULL

            next = cur->next;                                                         //dummy(p)-1   -1(c)-2(n)-2-NULL

            pre->next = cur;                                                          //dummy(p)     -1(c)-2(n)-2-NULL

        }

    }

    return dummyHead->next;

}

全部评论

相关推荐

05-01 22:41
中南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务