[leetcode]203. Remove Linked List Elements链表中删除节点

时间:2023-03-09 03:35:34
[leetcode]203. Remove Linked List Elements链表中删除节点

这道题很基础也很重要

重点就是设置超前节点

public ListNode removeElements(ListNode head, int val) {
//超前节点
ListNode pre = new ListNode(0);
pre.next = head;
ListNode res = pre;
while (pre!=null&&pre.next!=null)
{
if (pre.next.val==val)
{
pre.next = pre.next.next;
//注意这里要跳出循环,因为节点已经跳跃一位了,不需要再更新超前节点
continue;
}
pre = pre.next;
}
//这里不能返回head,因为head可能已经被孤立出来了
return res.next;
}