码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]82 Remove Duplicates from Sorted List II

时间:2015-01-04 19:30:52      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599020

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!