Remove Duplicates from Sorted List II

描述

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. // Remove Duplicates from Sorted List II
  2. // 递归版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *deleteDuplicates(ListNode *head) {
  6. if (head == nullptr || head->next == nullptr) return head;
  7. ListNode *p = head->next;
  8. if (head->val == p->val) {
  9. while (p != nullptr && head->val == p->val) {
  10. ListNode *tmp = p;
  11. p = p->next;
  12. delete tmp;
  13. }
  14. delete head;
  15. return deleteDuplicates(p);
  16. } else {
  17. head->next = deleteDuplicates(head->next);
  18. return head;
  19. }
  20. }
  21. };

迭代版

  1. // Remove Duplicates from Sorted List II
  2. // 迭代版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *deleteDuplicates(ListNode *head) {
  6. if (head == nullptr) return head;
  7. ListNode dummy(INT_MIN); // 头结点
  8. dummy.next = head;
  9. ListNode *prev = &dummy, *cur = head;
  10. while (cur != nullptr) {
  11. bool duplicated = false;
  12. while (cur->next != nullptr && cur->val == cur->next->val) {
  13. duplicated = true;
  14. ListNode *temp = cur;
  15. cur = cur->next;
  16. delete temp;
  17. }
  18. if (duplicated) { // 删除重复的最后一个元素
  19. ListNode *temp = cur;
  20. cur = cur->next;
  21. delete temp;
  22. continue;
  23. }
  24. prev->next = cur;
  25. prev = prev->next;
  26. cur = cur->next;
  27. }
  28. prev->next = cur;
  29. return dummy.next;
  30. }
  31. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/linked-list/remove-duplicates-from-sorted-list-ii.html