劍指offer:刪除鏈表中重複的結點

題目

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

解題

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead==null || pHead.next ==null)
            return pHead;

        ListNode preNode = null;
        ListNode pNode = pHead;
        while(pNode!=null){
            ListNode nextNode = pNode.next;
            boolean needDelete = false;
            // 找到刪除結點
            if(nextNode!=null&&nextNode.val==pNode.val){
                needDelete = true;
            }
            if(!needDelete){// 不須要刪除
                preNode = pNode; // 更新前驅節點
                pNode = pNode.next; // 當前結點後驗
            }else{ // 須要刪除
                int value = pNode.val; // 刪除結點的值
                ListNode toBeDel = pNode; // 找到下一個不須要刪除結點
            while(toBeDel!=null&&toBeDel.val == value){
                    nextNode = toBeDel.next;
                    toBeDel = nextNode;   
                }
            if(preNode==null)
                pHead = nextNode;
            else
                preNode.next = nextNode;
            pNode = nextNode;
          }
        }

        return pHead;
    }
}
相關文章
相關標籤/搜索