解法

有两个点需要注意,一个是设置个前节点,也就是自己创建一个节点然后连接到当前的链表上,然后就是链表删除的操作

实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
         ListNode pre=new ListNode(-1);
        ListNode res=pre;
        ListNode cur=head;
        pre.next=cur;
        while(cur!=null)
        {
            if(cur.val!=val)
            {
                pre=cur;
                cur=cur.next;
            }else
            {
                pre.next=cur.next;
                cur=cur.next;
            }
        }
        return res.next;
    }
}