203. 移除链表元素🔖链表

203. 移除链表元素🔖链表

https://leetcode.cn/problems/remove-linked-list-elements/description/递归java代码实现/** * public class ListNode { * int val; * ListNode next;...

2020年11月30日
164字
8 阅读

递归

java代码实现

/**
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
  public ListNode removeElements(ListNode head, int val) {
    // 将整个链表想象成head+子链表
    if (head == null)
      return null;
    // 先处理子链表
    head.next = removeElements(head.next, val);
    // 再处理头结点
    return head.val == val ? head.next : head;
  }
}

typescript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function removeElements(head: ListNode | null, val: number): ListNode | null {
  if (!head) return null
  head.next = removeElements(head.next, val)
  return head.val === val ? head.next : head
};

文章评论区

欢迎留言交流

未登录,请先注册或登录后发表评论。

Leave comment