[LeetCode] 82 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.

解题思路:

新建一个辅助表头,使用两个指针pre,p;

image

开始循环判断

1. pre->next=p->next,说明有相同的元素,则p=p->next;知道p->next为空或者发现新的元素;

image

2.判断 p->next!=p ,如果有相同元素的则p必然会向后移动,那么判断成立,pre->next=p->next,连接新的元素;

image

3.p未发生移动,则pre=pre->next,加入这个元素

image

代码:

/**

 * 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) {

        if(head==NULL)return NULL;

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

        ListNode *newlist=new ListNode(0);

        newlist->next=head;

        ListNode *pre=newlist;

        ListNode *p=head;

        while(p!=NULL)

        {

            while(p->next!=NULL&&pre->next->val==p->next->val)

                p=p->next;

            if(pre->next==p)    //未发生移动

                pre=pre->next;

            else                        //发生移动 要去除

            {

                pre->next=p->next;

            }

            p=p->next;

            //pre=pre->next;

        }

            return newlist->next;

    }

};

你可能感兴趣的:(LeetCode)