题意略:
思路都在注解里:
#include<iostream> #include<cstdio> 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; ListNode *pre = new ListNode(665); pre->next = head; //在head前面新建,就不用特判head;而且已经可以却行第一个点不同于前两个点 ListNode *p = pre, *q; while (p->next&&p->next->next){ //下面有用到后面两个节点,防止溢出 if (p->next->val == p->next->next->val){ q = p->next->next->next; //跳到第4个 while (q&&p->next->val == q->val)q = q->next; //相同段 p->next = q; //更改,删除相同段落 } else{ p = p->next; } } return pre->next; } };