82 remove duplicates from sorted list II

考虑到头两个可能就是重复,申请使用一个dummy节点,
1 ,当遇见前后重复的节点就删除当前节点,并记录下重复节点的val.
2, 下次遍历如果遇见当前节点的值和dup val一样,就删除当前节点

*没有释放被删除节点,下次改进

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
 
    if(head == NULL)
        return NULL;
    struct ListNode *dummy = calloc(1, sizeof(struct ListNode));
    dummy->next = head;

    struct ListNode * prev, * curr, *next, *dup;
    struct ListNode *tmp;

    prev = dummy;
    curr = dummy->next;
    next = curr->next;
    dup = NULL;

    while(curr){
        if(dup && curr->val == dup->val){

            tmp = curr;
            curr = curr->next;
            free(tmp);
            if(curr)
                next = curr->next;
            else
                next = NULL;
            prev->next = curr;
        }else if((next && next->val == curr->val)){
            //delete next
            prev->next = next->next;
            
            //mark duplicate value
            if(dup == NULL)
                dup = calloc(1,sizeof(ListNode));
            dup->val =  next->val;
            tmp = next;
            free(tmp);
            curr = prev->next;
            if(curr)
                next = curr->next;
            else
                next = NULL;
        }else{
            curr = curr->next;
            if(curr)
                next = curr->next;
            else
                next = NULL;
            prev = prev->next;
        }
    }

    
    struct ListNode * tmp2 = dummy->next;
    free(dummy);
    return tmp2;
}

你可能感兴趣的:(82 remove duplicates from sorted list II)