Remove Element from Linked List

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

Solution

public class Solution {
    /**
     * @param head a ListNode
     * @param val an integer
     * @return a ListNode
     */
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        while(head!=null) {
            if(head.val != val) {
                pre.next = head;
                pre = pre.next;
            }
            head = head.next;
        }
        // this is important
        pre.next = null;
        return dummy.next;
    }
}

results matching ""

    No results matching ""