剑指offer-删除链表中重复结点

问题描述:

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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)
    {
        if(!pHead)    return pHead;
        ListNode *pre = nullptr, *cur = pHead, *nex = nullptr;
        while(cur){
            nex = cur->next;
            if(nex && nex->val==cur->val){
                while(nex->next && nex->next->val==cur->val)    nex = nex->next;
                if(cur==pHead)    pHead = nex->next;
                else    pre->next = nex->next;
                cur = nex->next;
            }
            else{
                pre = cur;
                cur = cur->next;
            }
        }
        return pHead;
    }
};
发布了73 篇原创文章 · 获赞 11 · 访问量 9473

猜你喜欢

转载自blog.csdn.net/fanyuwgy/article/details/104021980
今日推荐