leetcode-203.移除链表元素

leetcode-203.移除链表元素

题目描述

在这里插入图片描述

代码提交

在这里插入图片描述

代码

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummyhead = new ListNode(0); // 设置一个虚拟头结点,堆上
        dummyhead->next = head;
        ListNode *cur = dummyhead; // 设置一个当前临时结点,栈上
        while (cur->next != nullptr) {
            if (cur->next->val == val) {
                ListNode *tmp = cur->next; // 设置一个临时结点,栈上
                cur->next = cur->next->next; 
                delete tmp; // 释放删除的节点空间
            } else {
                cur = cur->next;
            }
        }
        head = dummyhead->next;
        delete dummyhead; // 删除虚拟头节点
        return head;
    }
};

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>