题目:
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
.
思路:和Remove Duplicates from Sorted List I 类似,两个指针,从前向后检查。比较麻烦的地方在于,如果有duplcate,需要全部删除。具体做法是,runner指针在向前寻找的过程中,去找备选节点,然后判断,如果备选节点符合要求,那么加入到list中;若不符合,runner指针一直向后走到下一个备选节点,再重复上面的判断。
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == nullptr) return head;
ListNode dummy(0);
dummy.next = head;
ListNode* tail = &dummy;
ListNode* runner = head;
while (tail != nullptr) {
if (runner == nullptr || runner->next == nullptr || runner->val != runner->next->val) {
tail->next = runner;
tail = tail->next;
runner = runner == nullptr ? nullptr : runner->next;
} else {
while (runner->next != nullptr && runner->val == runner->next->val) {
runner = runner->next;
}
runner = runner->next;
}
}
return dummy.next;
}
};
总结:复杂度为O(n).