由于这个链表的头结点也是数据部分,为了保持删除操作的一致性在头结点前面加上一个扩展头节点指向数据头节点。
/**
* 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 headA = new ListNode(-1);//扩展的头结点
headA.next=head;
ListNode pre=headA,q=pre.next;
while(q!=null){
if(q.val==val){
pre.next=q.next;
break;
}
pre=pre.next;
q=q.next;
}
return headA.next;
}
}
原文:https://www.cnblogs.com/cstdio1/p/13295853.html