Remove Duplicates from Sorted List

描述

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

分析

递归版

  1. // Remove Duplicates from Sorted List
  2. // 递归版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *deleteDuplicates(ListNode *head) {
  6. if (!head) return head;
  7. ListNode dummy(head->val + 1); // 值只要跟head不同即可
  8. dummy.next = head;
  9. recur(&dummy, head);
  10. return dummy.next;
  11. }
  12. private:
  13. static void recur(ListNode *prev, ListNode *cur) {
  14. if (cur == nullptr) return;
  15. if (prev->val == cur->val) { // 删除head
  16. prev->next = cur->next;
  17. delete cur;
  18. recur(prev, prev->next);
  19. } else {
  20. recur(prev->next, cur->next);
  21. }
  22. }
  23. };

迭代版

  1. // Remove Duplicates from Sorted List
  2. // 迭代版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *deleteDuplicates(ListNode *head) {
  6. if (head == nullptr) return nullptr;
  7. for (ListNode *prev = head, *cur = head->next; cur != nullptr; cur = prev->next) {
  8. if (prev->val == cur->val) {
  9. prev->next = cur->next;
  10. delete cur;
  11. } else {
  12. prev = cur;
  13. }
  14. }
  15. return head;
  16. }
  17. };

相关题目

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