刪除單鏈表中的重複節點

1. 刪除重複節點,只保留一個

示例:code

Input: 1->1->2
Output: 1->2

代碼:class

ListNode* deleteDuplicates(ListNode* head) {
    ListNode *pre = head, *cur = head;
    while (cur) {
        if (pre->val != cur->val) {
            pre->next = cur;
            pre = pre->next;
        }
        cur = cur->next;
    }
    if (pre) pre->next = nullptr;
    return head;
}

2. 刪除所有重複節點

示例:List

Input: 1->2->3->3->4->4->5
Output: 1->2->5

代碼:next

ListNode* deleteDuplicates(ListNode* head) {
    ListNode *dummy = new ListNode(-1);
    dummy->next = head;
    ListNode *pre = dummy, *cur = head;
    while (cur) {
        while (cur->next && cur->next->val == cur->val)
            cur = cur->next;
        if (pre->next == cur)
            pre = cur;
        else
            pre->next = cur->next;
        cur = cur->next;
    }
    return dummy->next;    //不能直接返回 head,由於 head 有可能被刪除
}
相關文章
相關標籤/搜索