File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments