题目描述:(链接)
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 /** 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 public: 11 ListNode* deleteDuplicates(ListNode* head) { 12 if (!head || !(head->next)) return head; 13 14 ListNode *p = head->next; 15 if (head->val == p->val) { 16 while (p && head->val == p->val) { 17 ListNode *tmp = p; 18 p = p->next; 19 delete tmp; 20 } 21 delete head; 22 return deleteDuplicates(p); 23 } else { 24 head->next = deleteDuplicates(head->next); 25 return head; 26 } 27 } 28 };
迭代版:2015-10-27
1 class Solution { 2 public: 3 ListNode* deleteDuplicates(ListNode* head) { 4 if (!head || !(head->next)) return head; 5 6 ListNode dummy(-1); 7 ListNode *prev = &dummy; 8 ListNode *cur = head; 9 bool isDuplicated = false; 10 while (cur != nullptr) { 11 isDuplicated = false; 12 while (cur->next != nullptr && cur->val == cur->next->val) { 13 isDuplicated = true; 14 cur = cur->next; 15 } 16 17 if (isDuplicated) { 18 cur = cur->next; 19 continue; 20 } 21 22 prev->next = cur; 23 prev = prev->next; 24 cur = cur->next; 25 26 } 27 28 prev->next = cur; 29 30 return dummy.next; 31 } 32 };