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

要求

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

代码实现

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
#include <iostream>
using namespace::std;
//1,2,3,3,4,5 -> 1,2,3,4,5
  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* pre = head;
            ListNode* p = pre->next;
            while (p!=NULL) {
                if (pre->val==p->val) {
                    pre->next = p->next;
                    p = p->next;
                }else{
                    pre = pre->next;
                    p = p->next;
                }
            }
            return head;
        }
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}

Comments