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.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode deleteDuplicates(ListNode head) {
  11. if (head == null) {
  12. return null;
  13. }
  14. ListNode fake = new ListNode(0);
  15. ListNode p = fake;
  16. ListNode slow = head;
  17. ListNode fast = head;
  18. while (fast != null) {
  19. int count = 0;
  20. while (fast != null && fast.val == slow.val) {
  21. count++;
  22. fast = fast.next;
  23. }
  24. if (count == 1) {
  25. p.next = slow;
  26. p = p.next;
  27. }
  28. slow = fast;
  29. }
  30. p.next = null;
  31. return fake.next;
  32. }
  33. }