剑指 Offer 18 删除链表的节点

标签: 剑指 Offer 发布于:2022-02-23 10:52:13 编辑于:2022-02-23 10:52:13 浏览量:847

概述

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;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/