1.首先判断链表是不是为空
2.判断链表的头部是不是目标元素
3.设定上一个节点和当前节点,当前节点为空,循环结束
4.如果当前节点为目标节点,上一个节点指向当前节点的下一个节点,当前节点更新为下一个节点;如果不是的话,当前节点和上一个节节点后移
public static ListNode removeElements(ListNode head, int val) {
while(head!=null&&head.val==val){
head=head.next;
}
if(head==null){
return head;
}
ListNode before=head;
ListNode cur=head.next;
while(cur!=null){
if(cur.val==val){
before.next=cur.next;
}else {
before=cur;
}
cur=cur.next;
}
return head;
}