解题思路:创建一个假的头节点dummy节点指向head
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head==null) return null;
if(head.val==val) return head.next;
ListNode dummy=head;
while(head!=null&&head.next!=null){
if(head.next.val==val) head.next=head.next.next;
else head=head.next;
}
return dummy;
}
}
法二:递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head==null) return null;
if(head.val==val) return head.next;
head.next=deleteNode(head.next,val);
return head;
}
}