题解 | #删除链表中重复的结点#

删除链表中重复的结点

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        if (pHead == nullptr || pHead->next == nullptr) {
            return pHead;
        }
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = pHead;
        ListNode* pCur = dummyHead;
        while (pCur->next != nullptr && pCur->next->next != nullptr) {
            // 相邻节点值相同
            if (pCur->next->val == pCur->next->next->val) {
                int tmp = pCur->next->val;
                // 将所有相同的跳过
                while (pCur->next != nullptr && pCur->next->val == tmp) {
                    pCur->next = pCur->next->next;
                }
            } else {
                pCur = pCur->next;
            }
        }
        ListNode* res = dummyHead->next;
        delete dummyHead;
        return res;
    }
};

2023 剑指-链表 文章被收录于专栏

2023 剑指-链表

全部评论

相关推荐

程序员小白条:太晚了,看别人找到实习了才投的话,自己本身就没啥准备,计划太晚咯,只能吞苦果子
点赞 评论 收藏
分享
07-15 14:14
门头沟学院 Java
7.10投递7.15感谢信
投递地平线等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务