Sword refers to Offer 18. Delete the node of the linked list
Method one: double pointer
/**
* 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) {
ListNode i=new ListNode(-1);
i.next=head;
ListNode pre=i;
ListNode cur=i.next;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
return i.next;
}
cur=cur.next;
pre=pre.next;
}
return i.next;
}
}
Method Two:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head==null) return head;
if(head.val==val) return head.next;
head.next=deleteNode(head.next,val);
return head;
}
}