18.2 删除链表中重复的结点

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        if(pHead == nullptr || pHead->next == nullptr) return pHead;
        auto fake = new ListNode(0);
        auto left = pHead;
        auto right = pHead->next;
        auto pre = fake;
        bool duplicated = false;
        while(right){
            if(left->val == right->val){
                duplicated = true;
            }else{
                if(!duplicated){
                    pre->next = left;
                    pre = pre->next;
                }else{
                    duplicated = false;
                }
            }
            left = right;
            right = right->next;
        }
        if(!duplicated){
            pre->next = left;
            pre = pre->next;
        }
        pre->next = nullptr;
        return fake->next;
    }
};
posted @ 2021-03-27 20:35  rxh1999  阅读(30)  评论(0编辑  收藏  举报