2019-09-13[剑指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 == NULL)
        {
            return NULL;
        }
        // 判断是否只有一个节点
        if (pHead->next == NULL)
        {
            return pHead;
        }
        
        // 我们采用带头链表,自己添加一个头
        ListNode* pre_head = new ListNode(1);
        pre_head->next = pHead; // 把头节点链接在链表上
        ListNode* pre = pre_head;
        ListNode* cur = pHead; //中指针
        ListNode* nex = pHead->next; // 后面指针
        while (nex != NULL) // 结束条件
        {
            while (nex != NULL && cur->val == nex->val) 
            {
                nex = nex->next;
            }
            // 如果没有重复的那么cur的next一定等于nex
            if (cur->next != nex) // 如果相等说明没有相同的节点
            {
                while (cur != nex) // 删除动作
                {
                    pre->next = cur->next;
                    delete cur;
                    cur = pre->next;
                }
                if (nex != NULL)
                {
                    nex = nex->next;
                }
            }
            else
            {
                // 处理没有重复的情况
                pre = cur;
                nex = nex->next;
                cur = cur->next;
            }
        }
        ListNode* head = pre_head->next; // 释放空间,防止内存泄漏
        delete pre_head;
        return head;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容