LeetCode | Remove Duplicates from Sorted List II(删除链表中重复结点2)


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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

题目解析:

这道题看似简单,但却越到了很大的麻烦。时常少些必要的条件,经过修修补补,终于通过了……但不是一个好的方法。先贴上笨蛋方法……

利用flag来标记是否重复,以便后面进行修正。

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        int flag = 0;

        if(head == NULL || head->next == NULL)
            return head;

        ListNode *p,*q;
        p = head;
        q = p->next;

        head = NULL;
        while(q != NULL){
            if(p->val == q->val){
                flag = 1;
                q = q->next;
                continue;
            }
            if(flag == 1){
                flag = 0;
                p->val = q->val;
                p->next = q->next;
                if(head == NULL)
                    head = p;
                q = q->next;
                continue;
            }
            if(head == NULL)
                head = p;
            p->next = q;
            p = q;
            q = q->next;
        }
        
        if(head == NULL || (flag && head == p))
            return NULL;
        if(flag){
            ListNode *h = head;
            while(h->next != p)
                h = h->next;
            h->next = NULL;
        }
        return head;
    }
};

方案二:

很好的方法,利用二级指针来修改。ppNext = &(head->next)。这样赋值以后,便不随head的改变而改变,其就是一个指针的地址。

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode *root = NULL;
        ListNode **ppNext = &root;
        while(head) {
            if(head->next == NULL || head->next->val != head->val) {
                *ppNext = head;
                ppNext = &(head->next);
                head = head->next;
            } else {
                int val = head->val;
                do {
                    head = head->next;
                } while(head != NULL && head->val == val);
            }
        }
        *ppNext = NULL;
        return root;
    }
};


或者:

class Solution {  
public:  
    ListNode *deleteDuplicates(ListNode *head) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function      
        if(!head) return head;  
          
        int val = head->val;         
        ListNode ** pp = &head;  
        ListNode * cur = head;  
          
        if( cur->next == NULL || cur->next->val != cur->val  ) {  
            *pp = cur;  
            pp = &(cur->next);  
        }  
      
        while( (cur=cur->next) != NULL  ) {  
            if( cur->val != val) {  
                if( cur->next == NULL || cur->next->val != cur->val) {  
                    *pp = cur;  
                    pp = &(cur->next);  
                }  
                val = cur->val;  
            }  
        }  
          
        *pp = NULL;  
        return head;  
    }  
};  

点赞