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){
        if(head == null){return null;}

        //May remove the head node, so we use dummy to simply the process
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;

        while(head.next != null){
            if(head.next.val == val){
                head.next = head.next.next;
            }else{
                head = head.next;
            }
        }

        return dummy.next;
    }

results matching ""

    No results matching ""