1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 ListNode* deleteDuplication(ListNode* pHead) 13 { 14 auto dummy=new ListNode(INT_MIN); 15 dummy->next=pHead; 16 auto cur=dummy; 17 while(cur->next and cur->next->next){ 18 if(cur->next->val==cur->next->next->val){ 19 auto nex=cur->next; 20 int temp=cur->next->val; 21 while(nex and nex->val==temp){ 22 nex=nex->next; 23 } 24 cur->next=nex; 25 } 26 else{ 27 cur=cur->next; 28 } 29 } 30 return dummy->next; 31 } 32 };
写法2:
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 ListNode* deleteDuplication(ListNode* pHead) 13 { 14 auto dummy=new ListNode(INT_MIN); 15 dummy->next=pHead; 16 auto final_unique=dummy,cur=pHead,pre=dummy; 17 while(cur){ 18 if(cur->next and cur->val==cur->next->val){ 19 while(cur->next and cur->val==cur->next->val){ 20 cur=cur->next; 21 } 22 //此时cur为最后一个重复节点 23 } 24 else{ 25 final_unique->next=cur; 26 final_unique=cur; 27 } 28 cur=cur->next; 29 } 30 final_unique->next=nullptr; 31 return dummy->next; 32 } 33 };
原文:https://www.cnblogs.com/FdWzy/p/12305076.html