LeetCode: 移除链表元素

题目:
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回新的头节点
在这里插入图片描述

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head != nullptr && head->val == val)//删除头节点
        {
            ListNode*tmp = head;
            head = head->next;
            delete tmp;
        }
        ListNode*cur = head;
        while(cur != nullptr &&cur->next != nullptr)//删除非头节点
        {
            if(cur->next->val == val)
            {
                ListNode*tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            }
            else cur = cur->next;
        }
        return head;
    }
};
posted @ 2021-10-19 15:43  simonlma  阅读(11)  评论(0)    收藏  举报