删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
比如说 目标值val=3
删除3
2 3 4
head
head.next.val==3?to delete
head.next=head.next.next
首部怎么办?
搞个伪头(哨兵)
0 2 3 4
sentiel head
即
sentiel.next.val==val? to detele
sentiel.next=head.next
: sentiel=head,head=head.next
官方解释
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode sentinel = new ListNode(0);
sentinel.next = head;
ListNode prev = sentinel, curr = head;
while (curr != null) {
if (curr.val == val) prev.next = curr.next;
else prev = curr;
curr = curr.next;
}
return sentinel.next;
}
}
妙啊~