mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
添加 0203.移除链表元素递归解法 C++ 实现
This commit is contained in:
@ -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)
|
||||
|
||||
|
||||
## 其他语言版本
|
||||
|
Reference in New Issue
Block a user