删除链表中的重复结点 Apare_xzc

排序链表去重

2020.7.5

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        ListNode * p = pHead;
        ListNode * t, *q;
        if(!p||(p&&!p->next)) return pHead;
        t = p->next;
        while(t) {
            if(t->val!=p->val) p = p->next,t=t->next;
            else {
                p->next = t->next;
                delete t;
                t = p->next;
            }
        }
        return pHead;
    }
    //1->2->3->3->4->4->5
    //变成
    //1->2->3->4->5
};

删除重复的结点
递归实现,每次删除开头重复的所有结点

1->2->3->3->4->4->5 处理后为 1->2->5

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        ListNode * p = pHead;
        ListNode * t, *q;
        if(!p||(p&&!p->next)) return pHead; //空表或者只有一个元素
        t = p->next;
        if(p->val!=t->val) {
            p->next = deleteDuplication(t);
            return pHead;
        }
        int val = p->val;
        while(p) {
            if(p->val==val) {
                pHead = p->next;
                delete p;
                p = pHead;
            }
            else {
                pHead = deleteDuplication(pHead);
                return pHead;
            }
        }
        return nullptr;
    }
};

你可能感兴趣的:(删除链表中的重复结点 Apare_xzc)