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

在这里插入图片描述

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
    
    
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
    
    
        if(pHead==NULL||pHead->next==NULL)
            return pHead;
        
        ListNode* prev=NULL;
        ListNode* cur=pHead;
        ListNode* next=cur->next;
        
        while(next)
        {
    
    
            if(cur->val!=next->val)
            {
    
    
                prev=cur;
                cur=next;
                next=next->next;
            }
            else
            {
    
    
                while(next && cur->val ==next->val)
                {
    
    
                    next=next->next;
                }
                if(prev==NULL)
                {
    
    
                    pHead=next;
                }
                else
                {
    
    
                    prev->next=next;
                }
                
                //释放
                while(cur!=next)
                {
    
    
                    ListNode* del=cur;
                    cur=cur->next;
                    free(del);
                }
                
                if(cur)
                    next=cur->next;
            }
        }
        return pHead;

    }
};

猜你喜欢

转载自blog.csdn.net/qq_45657288/article/details/111996734
今日推荐