• 【剑指offer】删除链表中重复的结点


    删除链表中重复的结点

    题目描述


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

    思路分析


    直接比较删除

    循环判断当前节点的后继节点与后继节点的后继节点的值是否相同。如果相同,继续往后判断接下来的相邻节点是否相同。将当前节点的next域赋值为第一个不相同的节点。

    if(cur->next->val == cur->next->next->val)
    {
    	int tmp = cur->next->val;
    	while(cur->next != NULL && cur->next->val == tmp)
    	{
    		cur->next = cur->next->next;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    代码


    /*
    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;
            ListNode* res = new ListNode(0);
            res->next = pHead;
            ListNode* cur = res;
            while(cur->next != NULL && cur->next->next!= NULL)
            {
                if(cur->next->val == cur->next->next->val)
            {
                int tmp = cur->next->val;
                while(cur->next != NULL && cur->next->val == tmp)
                {
                    cur->next = cur->next->next;
                }
            }
            else{
                cur = cur->next;
            } 
            }
            
            return res->next;
           
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    常见的Java上机面试题
    ActivitiListener
    vector迭代器失效问题
    Spring-IOC容器底层原理
    ​JavaScript中的多种进制与进制转换 ​
    xctf攻防世界 Web高手进阶区 upload1
    Java 集合 - Queue 接口
    fiddler抓包
    【Python】函数与模块
    指定vscode黏贴图片路径(VSCode 1.79 更新)
  • 原文地址:https://blog.csdn.net/gszhlw/article/details/125502414