Remove Duplicates from Sorted List II @LeetCode

2014-11-24 08:44:40 · 作者: · 浏览: 0
两点体会:1 在连标题中,灵活地运用虚拟表头会减少很多工作量 2 链表题往往在收尾处要多判断一下,防止corner case
package Level3;  
  
import Utility.ListNode;  
  
/** 
 * Remove Duplicates from Sorted List II 
 *  
 *  Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 

For example, 
Given 1->2->3->3->4->4->5, return 1->2->5. 
Given 1->1->1->2->3, return 2->3. 
 * 
 */  
public class S82 {  
  
    public static void main(String[] args) {  
        ListNode head = new ListNode(1);  
        ListNode n1 = new ListNode(2);  
        ListNode n2 = new ListNode(2);  
        ListNode n3 = new ListNode(3);  
        ListNode n4 = new ListNode(3);  
        ListNode n5 = new ListNode(4);  
        ListNode n6 = new ListNode(5);  
        head.next = n1;  
        n1.next = n2;  
        n2.next = n3;  
        n3.next = n4;  
        n4.next = n5;  
        n5.next = n6;  
          
        head.print();  
        ListNode h = deleteDuplicates(head);  
        h.print();  
    }  
  
    public static ListNode deleteDuplicates(ListNode head) {  
        if(head == null){  
            return null;  
        }  
          
        // 用dummyHead来增加一个虚拟表头有效地减少了工作量!!  
        ListNode dummyHead = new ListNode(Integer.MIN_VALUE);  
        dummyHead.next = head;  
        ListNode pre = dummyHead;  
        ListNode cur = pre.next;  
        ListNode next = cur.next;  
        boolean dup = false;        // 判断是否有重复  
          
        while(true){  
            if(next == null){  
                break;  
            }  
            if(cur.val != next.val){  
                if(dup){        // 如果有重复的,就跳过  
                    pre.next = next;  
                    dup = false;        // 恢复dup  
                }else{      // 否则同步更新pre  
                    pre = cur;  
                }  
                cur = next;  
                next = next.next;  
            }  
            else if(cur.val == next.val){  
                dup = true;  
                next = next.next;  
            }  
        }  
          
        // 扫尾工作,针对于例如{1,1}的情况,最后再判断一次  
        if(dup){  
            pre.next = next;  
        }  
        return dummyHead.next;  
    }  
  
}