刪除鏈表中重複的結點 Delete duplicated nodes in linked list

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

題解

這題看似很簡單,但是務必考慮如下情形:

  • 1->1
  • 1->1->2->2
  • 1->2->2->3->3
  • 空鏈表

另外,遍歷鏈表千萬不要爲了簡潔寫成for循環!我因爲這個出了bug,看了很久纔看出來。

代碼

class Solution {
    ListNode* dedup(ListNode* head) {
        int val = head->val;
        while (head && head->val == val) {
            head = head->next;
        }
        return head;
    }
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        if (pHead == NULL) return NULL;
        ListNode *p = pHead, *pBefore = NULL;
        while (p != NULL) {
            if (p->next && p->next->val == p->val) {
                if (pBefore) {
                    pBefore->next = dedup(p);
                    p = pBefore->next;
                    continue;
                } else {
                    pHead = dedup(p);
                    p = pHead;
                    continue;
                }
            }
            pBefore = p;
            p = p->next;
        }
        return pHead;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章