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 curr = head;
        while(head != null && head.val == val) head = head.next; //先判断头节点值是不是val
        while(curr != null && curr.next != null)
        {
            if(curr.next.val == val) 
                curr.next = curr.next.next; //删除节点
            else
                curr = curr.next;
        }
        return head;
    }

还可以使用递归方法,代码非常的简介

    public ListNode removeElements(ListNode head, int val) {
      if(head == null) return null;
      head.next = removeElements(head.next,val);
      return head.val == val ? head.next : head;
    }
原文地址:https://www.cnblogs.com/wxshi/p/7834494.html