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 static int wing=[]() 10 { 11 std::ios::sync_with_stdio(false); 12 cin.tie(NULL); 13 return 0; 14 }(); 15 16 17 class Solution 18 { 19 public: 20 ListNode* deleteDuplicates(ListNode* head) 21 { 22 if(head==NULL||head->next==NULL) 23 return head; 24 ListNode *pre=head,*beh=head->next; 25 while(beh) 26 { 27 if(pre->val==beh->val) 28 { 29 beh=beh->next; 30 pre->next=beh; 31 } 32 else 33 { 34 pre=beh; 35 beh=beh->next; 36 } 37 } 38 return head; 39 } 40 };
俩指针,前后节点值比较,相等的话,后指针后移,前指针的后继随之后移
不相等的话,俩指针同时后移,直到后指针为空表示链表扫描完毕