203. Remove Linked List Elements

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
//Time: O(n), Space: O(1)    
public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        
        ListNode dummy = new ListNode(0);//不要忘记头节点
        dummy.next = head;
        ListNode newHead = dummy;
        
        while (dummy != null && dummy.next != null) {
            if (dummy.next.val == val) {
                dummy.next = dummy.next.next;
            } else {//注意当dummy的next不等于val的时候才移动dummy,因为如果相等有可能下一个还相等要继续判断
                dummy = dummy.next;
            }
        }
        
        return newHead.next;
    }
原文地址:https://www.cnblogs.com/jessie2009/p/9811215.html