LeetCode 203 - Remove Linked List Elements

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

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

public ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(0);
    ListNode node = dummy;
    node.next = head;
    while(node != null && node.next != null) {
        if(node.next.val == val) {
            node.next = node.next.next;
        } else {
            node = node.next;
        }
    }
    return dummy.next;
}

 

你可能感兴趣的:(LeetCode 203 - Remove Linked List Elements)