203:删除链表中的所有指定元素

问题

Remove all elements from a linked list of integers that have value val.

Example:
Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

代码

/**
 * 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 listNode=new ListNode(-1);

        ListNode pre=listNode;
        pre.next=head;
        ListNode cur=head;
        while(cur!=null){
            if(cur.val==val){
                pre.next=cur.next;
            }else{ 
            pre=pre.next;

            }
           cur=cur.next;
        }
        return listNode.next;
    }
}