82. Remove Duplicates from Sorted List II

来源:互联网 发布:qq群机器人软件 编辑:程序博客网 时间:2024/05/29 19:30

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和后面的怎么连上,区分pre-1-1-2这种情况和pre-1-2这种情况。后面走的肯定能判断出来1-2不同了。前面怎么判断1是有重复的还是没重复的,主要通过pre->next是否等于当前循环的这个指针,如果等于说明前面没有重复的,如果不等于说明是经过重复循环过来的。

/** * 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 || head->next == NULL) return head;        ListNode *fakeHead = new ListNode(-1);        fakeHead->next = head;        ListNode *pre = fakeHead;        while(head!=NULL)        {            while(head->next!=NULL && head->next->val == head->val)            {                head = head->next;            }            if(pre->next != head)            {                pre->next = head->next;            }            else            {                pre = pre->next;            }            head = head->next;        }        return fakeHead->next;    }};
0 0