考略最笨的方法:遇到值相同的就删除一个。
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 if (!head) return NULL; 10 if (!head->next) return head; 11 12 struct ListNode *p = NULL; 13 struct ListNode *q = NULL; 14 struct ListNode *r = NULL; 15 struct ListNode *newHead = NULL;//newHead denotes the new list 16 int flag = 0, isHead = 0;//isHead=0 denotes there is no head in newHead 17 p = head, q = p->next;//p denotes the current node,q denotes the next node 18 19 flag = 0;//there are no duplications 20 while (q) 21 { 22 if (p->val != q->val && flag == 0)//put p in new list 23 { 24 if (!isHead) 25 { 26 newHead = r = p; 27 isHead = 1;//there is already head in newHead 28 r->next = NULL; 29 } 30 else 31 { 32 r->next = p; 33 r = p; 34 r->next = NULL; 35 } 36 } 37 else if (p->val != q->val && flag == 1)//delete p 38 flag = 0; 39 else if (p->val == q->val)//delete p 40 flag = 1; 41 42 p = q; 43 q = q->next; 44 } 45 46 if (flag == 1) 47 { 48 if (!isHead) 49 newHead == NULL; 50 else 51 r->next = NULL; 52 } 53 else 54 { 55 if (!isHead) 56 { 57 newHead = p; 58 newHead->next = NULL; 59 } 60 else 61 { 62 r->next = p; 63 r = p; 64 r->next = NULL; 65 } 66 } 67 68 return newHead; 69 }
LeetCode-Remove Duplicates from Sorted List II
原文:http://www.cnblogs.com/vdvvdd/p/5014372.html