203 Remove Linked List Elements

1. Question

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

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

2. Implementation

/**
 * 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 dummy = new ListNode(0);
        dummy.next = head;
        ListNode preNode = dummy, curNode = head;

        while (curNode != null) {
            if (curNode.val == val) {
                preNode.next = curNode.next;
            }
            else {
                preNode = preNode.next;
            }
            curNode = curNode.next;
        }
        return dummy.next;
    }
}

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)

Last updated