首页 > 代码库 > [LeetCode]82 Remove Duplicates from Sorted List II

[LeetCode]82 Remove Duplicates from Sorted List II

https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

http://blog.csdn.net/linhuanmars/article/details/24389429

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        
        if (head == null || head.next == null)
            return head;
            
        
        // 1 -> 2 -> 2 -> 3
        // pre  test testnext  next
        
        ListNode pre = null;
        ListNode test = head;
        ListNode testnext = test.next;
        boolean deletetest = false;
        
        ListNode newhead = null;
        
        while (test != null)
        {
            if (testnext != null && test.val == testnext.val)
            {
                // Delete testnext;
                deletetest = true;
                ListNode next = testnext.next;
                test.next = next;
                testnext.next = null;
                testnext = next;
            }
            else if (deletetest)
            {
                // Delete test
                deletetest = false;
                if (pre != null)
                {
                    pre.next = testnext;
                }
                test.next = null;
                test = testnext;
                if (test != null)
                    testnext = test.next;
            }
            else
            {
                pre = test;
                if (newhead == null)
                    newhead = test;
                test = testnext;
                if (test != null)
                    testnext = test.next;
            }
        }
        
        return newhead;
    }
}


[LeetCode]82 Remove Duplicates from Sorted List II