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

删除链表中重复的结点

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=265&tqId=39270&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=undefined&tags=&title=

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        if(pHead == nullptr){
            return nullptr;
        }
        //链表可仅通过一个指针,赋值next节点的内容到指针节点后删除next节点,以达到删除指针节点的效果;
        //但指针节点到链表末尾后无法进行该操作,而双指针在链表头部节点无法进行常规操作;
        //所以引入哨兵节点于链表前,以统一删除节点操作
        ListNode *front = pHead;
        ListNode *note = new ListNode(0), *behind = note;
        behind->next = front;
        while(front!=nullptr&&front->next!=nullptr){
            if(front->next->val != front->val){
                behind = behind->next;
                front = front->next;
            }else{
                while(front->next != nullptr&&front->next->val == front->val){
                    ListNode *temp = front->next;
                    front->next = front->next->next;
                    delete temp;
                }
                behind->next = front->next;
                delete front;
                front = behind->next;
            }
        }
        pHead = note->next;
        return pHead;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
赛博小保安:不行你就找点东西继续干干直接等明年走社招吧,学历差的在秋招真的没戏。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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