From c3541789614a1703154125f3e7a26592f5f2bc5e Mon Sep 17 00:00:00 2001 From: Lifan Sun Date: Thu, 25 Jul 2024 16:11:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0=E9=80=92=E5=BD=92=E8=A7=A3?= =?UTF-8?q?=E6=B3=95=20C++=20=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 64124fbb..f6b5ef6d 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -149,7 +149,35 @@ public: * 时间复杂度: O(n) * 空间复杂度: O(1) +**也可以通过递归的思路解决本题:** +基础情况:对于空链表,不需要移除元素。 + +递归情况:首先检查头节点的值是否为 val,如果是则移除头节点,答案即为在头节点的后续节点上递归的结果;如果头节点的值不为 val,则答案为头节点与在头节点的后续节点上递归得到的新链表拼接的结果。 + +```CPP +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + // 基础情况:空链表 + if (head == nullptr) { + return nullptr; + } + + // 递归处理 + if (head->val == val) { + ListNode* newHead = removeElements(head->next, val); + delete head; + return newHead; + } else { + head->next = removeElements(head->next, val); + return head; + } + } +}; +``` +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 其他语言版本