Friday, November 13, 2015

[leetcode] Remove Duplicates from Sorted List II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode current = head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode previous = dummy;
        boolean shouldClean = false;
        while (current != null){
         if (current.next != null && current.next.val == current.val){
          ListNode temp = current.next.next;
          current.next.next = null;
          current.next = temp;
          shouldClean = true;
         }else{
          if (shouldClean){
           previous.next = current.next;
        shouldClean = false;
          }else{
           previous = current;
          }
          current = current.next;
         }
        }
        return dummy.next;
    }
}

No comments:

Post a Comment