/**
* 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) {
// 创建一个节点指向头节点
ListNode result = new ListNode();
// 让result指向head
result.next = head;
// 创建一个移动的节点 让它指向head
ListNode pre = result;
// 移动head和pre
while(head !=null) {
if (head.val == val) {
pre.next = head.next;
head =head.next;
}
else{
pre = head;
head =head.next;
}
}
// 因为head和pre是移动的 只有result没有移动 所以返回result.next
return result.next;
}
}