递归
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
};
评论区