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 };
Two pointers, compare the values of the front and back nodes, if they are equal, the back pointer moves back, and the successor of the front pointer moves back subsequently
If they are not equal, the two pointers are moved backward at the same time, until the latter pointer is empty, indicating that the linked list is scanned.