Thursday, March 7, 2013

[LeetCode] Remove Duplicates from Sorted List II

Thought:
Basically the same with previous problem.

Code: 
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
       
        ListNode flag = new ListNode(0);
        flag.next = head;
       
        ListNode current = head;
        ListNode index = flag;
       
        while (current != null) {
            boolean delete = false;
            while (current.next != null && current.val == current.next.val) {
                current = current.next;
                delete = true;
            }
            if(delete) {               
                index.next = current.next;           
            }else {
                index = index.next;
            }
            current = current.next;
        }
       
        return flag.next;
    }
}

No comments:

Post a Comment