刪除鏈表中重複的節點(Java實現)

  • 問題描述

在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5

  • 解決方案

注意邊界即可,代碼如下:

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null)
            return pHead;
        //標記頭結點是否需要刪除,需要刪除,最後處理
        boolean flag =false;
        int temp = 0;
        if(pHead.next != null && pHead.next.val == pHead.val){
             flag = true;
            temp = pHead.val;
        }
        ListNode cur = pHead;
        ListNode del = null;
        while(cur.next != null && cur.next.next != null){
            if(del != null && cur.next.val == del.val){
                cur.next = cur.next.next;
            }
            else if(cur.next.next.val == cur.next.val){
                del = cur.next;
                cur.next = cur.next.next;
            }
            else
                cur = cur.next;
        }
        //處理最後一個節點需要刪除的情況  
        if(del != null && cur.next!= null && cur.next.val == del.val)
            cur.next = null;
        //處理頭結點需要刪除的情況    
        while(flag && pHead != null && pHead.val == temp)
            pHead = pHead.next;
        return pHead;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章