删除链表中等于给定值 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 null;
head.next=removeElements(head.next,val);
if(head.val==val) head=head.next;
//这里如果写成if(head.val==val) head=head.next;
// head.next=removeElements(head.next,val);
//就会出现空指针异常,因为这样写的话在没有判断head.next是否为空的情况下,
//就将其赋给head,所以会有空指针异常
return head;
}
}