1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution 10 { 11 public: 12 ListNode* deleteDuplicates(ListNode* head) 13 { 14 if(head==NULL) 15 return head; 16 ListNode *write=head,*read=head,*tail; 17 int count=0,cur=head->val,res=0; 18 while(read!=NULL) 19 { 20 if(read->val==cur) 21 { 22 count++; 23 read=read->next; 24 } 25 else 26 { 27 if(count==1) 28 { 29 write->val=cur; 30 tail=write; 31 write=write->next; 32 res++; 33 } 34 cur=read->val; 35 count=1; 36 read=read->next; 37 } 38 } 39 if(count==1) 40 { 41 write->val=cur; 42 tail=write; 43 write=write->next; 44 res++; 45 } 46 if(res==0) 47 return NULL; 48 else 49 { 50 tail->next=NULL; 51 return head; 52 } 53 } 54 };
双指针压缩链表,一个读指针,一个写指针,问题不大