删除链表的重复元素(二)

要求

删除链表中的重复元素,例如1->1->1->2->3->3->4->4->5,返回2->5

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;

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

        }
    }
};
int main(int argc, const char * argv[]) {
    return 0;
}

Comments