创建一个虚拟头结点 从虚拟头结点去遍历
public class Solution { public ListNode RemoveElements(ListNode head, int val) { ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode prev = dummyHead; while (prev.next != null) { if (prev.next.val == val) { prev.next = prev.next.next; } else { prev = prev.next; } } return dummyHead.next; } }