Leetcode----- 82.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 RemoveDuplicatesfromSortedListII {
    public static ListNode deleteDuplicates(ListNode head) {
    	if(head == null || head.next == null) {
    		return head;
    	}
    	ListNode ret = new ListNode(0);
    	ListNode node = ret;
    	ListNode pre = head;
    	ListNode point = head.next;
    	while(point != null) {
    		if(pre.val == point.val) {
    			while(point.next != null && point.next.val == pre.val) {
    				point = point.next;
    			}
				pre = point.next;
				ret.next = pre;
				point = point.next;
    		}else {
    			ret.next = pre;
    			pre = pre.next;
    			ret = ret.next;
    		}
    		if(point != null) {
    			point = point.next;	
    		} 			
    	}
        return node.next;
    }

	public static void main(String[] args) {
		ListNode l10 = new ListNode(1);
		ListNode l11 = new ListNode(1);
		ListNode l12 = new ListNode(1);		
		ListNode l13 = new ListNode(1);
		ListNode l14 = new ListNode(1);
		ListNode l15 = new ListNode(1);
		ListNode l16 = new ListNode(1);
		l10.next = l11;
		l11.next = l12;
		l12.next = l13;
		l13.next = l14;
		l14.next = l15;
		l15.next = l16;
		l16.next = null;
		
		ListNode node = deleteDuplicates(l10);
		while(node != null) {
			if(node.next == null) {
				System.out.println(node.val);
			}else{
				System.out.print(node.val +"->");
			}
			node = node.next;
		}
	}	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章