Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
要考慮多種情況比如:
1->1->1->3->3->3->3,
1->1->1
1->2->2->3,
1->2->2
設置3個指針,前指針pre和前前指針prepre指向頭結點,當前指pcur針指向頭結點下一個指針。
設置一個標志位FLAG,判斷pcur和pre是否相等過。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* deleteDuplicates(struct ListNode* head) { 9 struct ListNode* prepre; 10 struct ListNode* pre; 11 struct ListNode* pcur; 12 int flag = 0; //標志位初始化為0 13 if(head == NULL) 14 return NULL; 15 prepre = head; 16 pre = head; 17 pcur = head->next; 18 while(pcur != NULL){ 19 if(pcur->val != pre->val && flag == 0){ //如果前指針和當前指針不相等,並且之間沒有相同元素,3個指針都指向下一個 20 prepre = pre; 21 pre = pcur; 22 pcur = pcur->next; 23 } 24 else if(pcur->val == pre->val){ //如果前指針和當前指針相等 25 if(pcur->next == NULL){ //如果當前指針為最後一個元素 26 if(prepre == head && prepre->val == pcur->val) //判斷前前指針是否是頭結點,並且和當前元素是否相等判斷,比如1->1->1 27 return NULL; 28 else{ 29 prepre->next = NULL; 30 break; 31 } 32 } 33 flag = 1; 34 pcur = pcur->next; 35 } 36 else if(pcur->val != pre->val && flag == 1){ //如果前指針和當前指針不相等,之間有相同元素 37 if(prepre == head && prepre->val == pre->val){ //判斷前前指針是否是頭結點並且和前指針是否相等2->2->2->3 38 head = pcur; 39 prepre = head; 40 pre = pcur; 41 pcur = pcur->next; 42 flag = 0; 43 } 44 else{ 45 prepre->next = pcur; 46 pre = pcur; 47 pcur = pcur->next; 48 flag = 0; 49 } 50 } 51 } 52 return head; 53 }