Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
Example 2:
Input: 1->1->1->2->3 Output: 2->3
思路:
从头开始检测,当发现有重复的情况时就往后找直到没有重复的情况,并将重复的一段删除(就是排除在链表外)。代码如下:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode feakHead(0);
feakHead.next = head; head = &feakHead;
ListNode *curr = head;
while (curr->next){
if (curr->next->next && curr->next->val == curr->next->next->val){
ListNode* record = curr->next->next;
while (record->next && record->val == record->next->val){
record = record->next;
}
curr->next = record->next;
}
else curr = curr->next;
}
return head->next;
}
};
纪念贴图: