给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
列表中的节点在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= k <= 50
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
解决链表问题常规有两种方法,一种是直接遍历,一种是递归,直接遍历要注意头部有val以及中间连续val的情况,递归就很好理解了,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 如果为空
if(head == nullptr) {
return nullptr;
}
// 如果头部有val,先去除
while(head != nullptr && head->val == val) {
head = head -> next;
}
ListNode* node = head;
while(node != nullptr) {
// while循环防止连续的val出现
while(node->next != nullptr && node->next->val == val) {
node->next = node->next->next;
}
node = node->next;
}
return head;
}
};
/*作者:heroding
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/solution/cliang-chong-jie-fa-by-heroding-6djl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 如果为空
if(head == nullptr) {
return nullptr;
}
head->next = removeElements(head->next,val);
if(head->val == val) {
return head->next;
}
return head;
}
};
/*作者:heroding
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/solution/cliang-chong-jie-fa-by-heroding-6djl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/