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

题目描述 : 

代码如下 (附有解析 ):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
    if(!head||!head->next)
        return head;
    //使用一个头指针来防止返回时找不到头节点
    struct ListNode* ret=(struct ListNode*)malloc(sizeof(struct ListNode));
    ret->next=head;
    struct ListNode* prve=ret;
    //当prve走到最后一个元素时,证明删除结束
    while(prve->next){
        //更新cur
        struct ListNode* cur=prve->next;
        //cur走到最后一个重复数字
        while(cur->next&&cur->val==cur->next->val){
            cur=cur->next;
        }
        //当cur和prve不相邻时,证明中间有重复数字,然后将将中间相同元素跳过即可
        if(cur!=prve->next)
            prve->next=cur->next;
        //如果相邻直接证明中间无重复元素,直接进行下一趟循环
        else
            prve=prve->next;
    }        
    //返回头节点
    return ret->next;
}

猜你喜欢

转载自blog.csdn.net/ds19980228/article/details/82774930