203.删除链接列表元素
#初学者 #java #leetcode #linkedlist

给定链接列表和整数阀的头部,删除具有node.val == val的链接列表的所有节点,然后返回新的头。

示例1:

输入: head = [1,2,6,3,4,5,6],val = 6
输出: [1,2,3,4,5]
示例2:

输入:** head = [],val = 1
**输出:
[]

示例3:

输入: head = [7,7,7,7],val = 7
输出: []

约束:

列表中的节点数在[0,104]范围内。
1 <= node.val <= 50
0 <= val <= 50

解决方案:

class Solution {
    public ListNode removeElements(ListNode head, int val) {
       if (head == null)
            return null;

        ListNode curr = head;
        ListNode prev = null;

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