首页 > 其他 > 详细

[LeetCode]82 Remove Duplicates from Sorted List II

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!