题目描述
删除链表中等于给定值 val 的所有节点
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
思路
- dummy->next = head 是为了应对删除头结点的情况
- 必须考虑到val连续出现的情况
代码实现
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* curr = dummy;
while(curr != NULL && curr->next != NULL){
while(curr->next->val == val){
curr->next = curr->next->next;
if(curr->next == NULL) break;
}
curr = curr->next;
}
return dummy->next;
}
};
// 另解:递归
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL)
return head;
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};
执行结果
执行用时 : 36 ms, 在Remove Linked List Elements的C++提交中击败了98.26% 的用户
内存消耗 : 11 MB, 在Remove Linked List Elements的C++提交中击败了77.68% 的用户