Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cc1cdb0

Browse files
add java recursion version of 203
1 parent b3c79d8 commit cc1cdb0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎problems/0203.移除链表元素.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,37 @@ public ListNode removeElements(ListNode head, int val) {
337337

338338
```
339339

340+
递归
341+
342+
```java
343+
/**
344+
* 时间复杂度 O(n)
345+
* 空间复杂度 O(n)
346+
* @param head
347+
* @param val
348+
* @return
349+
*/
350+
class Solution {
351+
public ListNode removeElements(ListNode head, int val) {
352+
if (head == null) {
353+
return head;
354+
}
355+
356+
// 假设 removeElements() 返回后面完整的已经去掉val节点的子链表
357+
// 在当前递归层用当前节点接住后面的子链表
358+
// 随后判断当前层的node是否需要被删除,如果是,就返回
359+
// 也可以先判断是否需要删除当前node,但是这样条件语句会比较不好想
360+
head.next = removeElements(head.next, val);
361+
if (head.val == val) {
362+
return head.next;
363+
}
364+
return head;
365+
366+
// 实际上就是还原一个从尾部开始重新构建链表的过程
367+
}
368+
}
369+
```
370+
340371
### Python:
341372

342373
```python

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /