代码随想录 203. 移除链表元素

47 阅读1分钟

203. 移除链表元素 - 力扣(LeetCode)

手把手带你学会操作链表 | LeetCode:203.移除链表元素_哔哩哔哩_bilibili

原链表删除

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
    if(head==NULL)return head;
    ListNode* cur=head;
   
   while(head&&head->val==val)head=head->next;

    while(cur&&cur->next)
    {
        if(cur->next->val==val)cur->next=cur->next->next;
            else cur=cur->next;
    }


return head;
    }
};

虚拟头节点

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
            if(head==nullptr)return head;
            ListNode* dummy=new ListNode(0);
            ListNode* cur=dummy;
            dummy->next=head;
            while(cur&&cur->next)
            {
                if(cur->next->val==val)
                {
                    cur->next=cur->next->next;
                }
                else cur=cur->next;
            }

            return dummy->next;
    }
};