/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
//判空(可有可无)
// if(head==null){
// return null;
// }
//不带虚拟节点
//先单独判断头节点是否等于val
while(head!=null&&head.val==val){
head=head.next;
}
//if head.next 为空,直接跳过下个循环,return null
//确定头节点不为空
ListNode curr = head;
while(curr!=null){
while(curr.next!=null&&curr.next.val==val){
curr.next=curr.next.next;
}
//curr的值不为val,不删除
curr = curr.next;
}
//if curr 为空,直接跳过下个循环,return null
return head;
}
}
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
// 已经为null,提前退出
if (head == null) {
return head;
}
// 已确定当前head.val != val
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return head;
}