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 ListNode deleteDuplicates(ListNode head) {
  5. if (head ==null || head.next == null) return head;
  6. ListNode p = head.next;
  7. if (head.val == p.val) {
  8. while (p != null && head.val == p.val) {
  9. p = p.next;
  10. }
  11. return deleteDuplicates(p);
  12. } else {
  13. head.next = deleteDuplicates(head.next);
  14. return head;
  15. }
  16. }
  17. };

迭代版

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

相关题目

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