参考链接
- https://leetcode-cn.com/problems/remove-linked-list-elements/
- https://leetcode-cn.com/problems/remove-linked-list-elements/solution/yi-chu-lian-biao-yuan-su-by-leetcode-sol-654m/
题目描述
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
解题思路
最简单的思路是,新建一个头结点,如果原链表某节点的值不等于val,则将该节点加入新链表。还可以使用递归的思路,但是会额外消耗栈空间。
代码
迭代法
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *newhead = new ListNode(0, nullptr);
ListNode* p = newhead;
while (head != nullptr)
{
if (head->val != val)
{
p->next = head;
p = p->next;
}
head = head->next;
}
p->next = nullptr;
return newhead->next;
}
};
递归法
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr) {
return head;
}
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};