剑指 Offer 18 删除链表的节点
概述
https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
迭代法
题目保证了一定存在目标值,所以我们的 while 循环不需要检查 nullptr。
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        auto dummyHead = new ListNode;
        dummyHead->next = head;
        auto c = dummyHead;
        while (c->next->val != val) c = c->next;
        c->next = c->next->next;
        return dummyHead->next;
    }
};
递归法
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if (head->val == val) return head->next;
        head->next = deleteNode(head->next, val);
        return head;
    }
};
Links: sword-offer-18