- 移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.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)
return nullptr;
while(head){
if(head->val == val)
head = head->next;
else{
break;
}
}
if(!head)
return nullptr;
ListNode* root = head->next;
ListNode* parent = head;
ListNode* result = head;
while(root){
if(root->val == val){
parent->next = root->next;
root = root->next;
}else{
parent = parent->next;
root = root->next;
}
}
return result;
}
};
经验: 水题,迭代递归均可。