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
删除单链表中所有数据域为给定val的节点:
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head==null) return null;//判断链表是否为空
ListNode p = head;//定义一个指针指向头节点
while (p.next!=null){
if(p.next.val==val) p.next=p.next.next;//将待删节点的前一节点的指针指向待删节点的后一节点
else p=p.next;}
return head.val == val ? head.next : head;//返回头节点
}
}