劍指Offer題目:刪除鏈表中重複的結點

劍指Offer題目:刪除鏈表中重複的結點

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


解題思路

思路:利用雙指針,首先建立一個虛擬頭結點vroot,然後設置兩個指針precur
pre指向確定不會重複的結點,cur作爲工作指針不斷向後搜索。最後結果返回vroot的下一結點。


完整代碼

public class q57_deleteDuplication_刪除鏈表中重複的結點 {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) return pHead;
        ListNode vroot = new ListNode(-1);
        vroot.next = pHead;
        ListNode pre = vroot;
        ListNode cur = pHead;
        while (cur != null) {
            //有元素重複
            if (cur.next != null && cur.next.val == cur.val) {
                //向後搜索,直到鏈表末尾或者和下一個元素不相等
                while (cur.next != null && cur.next.val == cur.val) {
                    cur = cur.next;
                }
                //將pre指針指向cur的下一元素,該元素確定不會和它的前驅結點元素相等
                pre.next = cur.next;
                cur = cur.next;
            }
            //當前結點爲鏈表末尾結點或者當前元素和下一元素不相等,當前結點就是唯一的結點
            else {
                //pre指針指向該元素,並繼續向下查找
                pre.next = cur;
                pre = pre.next;
                cur = cur.next;
            }
        }
        return vroot.next;
    }
}

更多LeetCode題目及答案解析見GitHub: https://github.com/on-the-roads/LeetCode
劍指offer題目及答案解析:https://github.com/on-the-roads/SwordToOffer

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