牛客网剑指Offer——删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

解题思路

1、由于存在重复的节点都要删除,那么头结点也有可能被删除,因此需要创建新的头结点head;
2、写的比较复杂,用了三个指针,不过大概思路是一样的。需要三个指针:pre,cur和next(pre = cur;cur = pre->next;next = cur->next;)。遍历链表,每遍历一个结点cur,且cur!=NULL,做以下判断:
如果它的下个结点next不为空,且cur->val和next->val相等,那么说明这两个是重复的结点,则next = next->val,直到cur->val和next->val不相等为止;然后删除从pre->next到next之间的节点。
否则,pre = cur;cur = pre->next;next = cur->next;(注:写next = cur->next前需要判断cur是否为NULL

代码

/*
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* head = new ListNode(0);
        head->next = pHead;
        ListNode* pre = head;
        ListNode* cur = pre->next;
        ListNode* next = cur->next;

        while( cur )
        {
            if( next && next->val == cur->val )
            {
                while( next && next->val == cur->val )
                    next = next->next;
                pre->next = next;
                while( cur != pre->next )
                {
                    next = cur->next;
                    delete cur;
                    cur = next;
                    if( cur )
                        next = cur->next;
                }
                cur = pre->next;
                if( cur )
                    next = cur->next;
            }
            else
            {
                pre = cur;
                cur = pre->next;
                if( cur )
                    next = cur->next;
            }
        }

        return head->next;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36132127/article/details/80157984
今日推荐