leetcode分类下所有的题解均为作者本人经过权衡后挑选出的题解,在易读和可维护性上有优势
每题只有一个答案,避免掉了太繁琐的以及不实用的方案,所以不一定是最优解
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}
思路:
- 如果head.val等于val的话就传递head.next,相当于跳过这个节点