[LeetCode]Remove Duplicates from Sorted List II

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.

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode *deleteDuplicates(ListNode *head) {

        ListNode *p,*q,*r; //前中后

        ListNode *newhead=NULL,*n;

        if(head==NULL||head->next==NULL) return head; //空链表,单结点直接返回

        p=head;

        q=p->next;

        r=q->next;

        if(head->val!=head->next->val) newhead=n=head; //若头结点不需要去掉

        if(r==NULL) //两个结点

        {

            if(p->val==q->val) return NULL; 

            else return head;

        }

        while(r)

        {

            if(p->val!=q->val&&q->val!=r->val) //前后不同,新链表加入q

            {

                if(newhead==NULL)

                {

                    newhead=n=q;

                }

                else 

                {

                    n->next=q;

                    n=q;

                }

            }

            p=p->next;

            q=q->next;

            r=r->next;

        }

        //r==NULL

        if(p->val!=q->val) //考虑无头结点情况

        {

            if(newhead==NULL)

            {

                newhead=q;

                newhead->next=NULL;

                return newhead;

            }

            else n->next=q;

        }

        else 

        {

            if(newhead==NULL) return newhead;

            else 

            {

                n->next=q;

                n->next=NULL;

            }

        }

        return newhead;

    }

};

  

你可能感兴趣的:(LeetCode)