LeetCode Solutions : Remove Duplicates from Sorted List II

【題目描述】

Given a sortedlinked list, delete all nodes that have duplicate numbers, leaving only distinct numbersfrom 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.

【編程步驟】

 * 1. 處理特殊情況:如果該鏈表爲空或只有一個結點,說明此鏈表沒有重複的元素,直接返回頭指針head

即:if(head==null||head.next==null) 
            return head;
 * 2.
設置僞頭結點;

即:ListNode pre=new ListNode(0);
              pre.next=head;
              head=pre;

 * 3. cur=pre.next,若不存在複本,cur依然爲pre.next;若存在複本,cur指向複本的下一個不等於它本身值的結點,並作移除操作;  

	ListNode cur=pre.next;
			while(cur.next!=null&&cur.next.val==cur.val)
				cur=cur.next;
			if(pre.next==cur){ // don't find the duplicate
				pre=pre.next;
			}else{ //remove the duplicate node
				pre.next=cur.next;
			}

 * 4. 返回head.next,因爲此時的head爲僞頭結點;

【代碼實現】

/**
 * 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;
		ListNode pre=new ListNode(0);
		pre.next=head;
		head=pre;		
		while(pre.next!=null){
			ListNode cur=pre.next;
			while(cur.next!=null&&cur.next.val==cur.val)
				cur=cur.next;
			if(pre.next==cur){ // don't find the duplicate
				pre=pre.next;
			}else{ //remove the duplicate node
				pre.next=cur.next;
			}
		}
		return head.next;
    }
}


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