https://leetcode.com/problems/remove-linked-list-elements/description/
题目描述: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 static ListNode removeElements(ListNode head, int val) {
if(head==null){
return null;
}
ListNode node = head;
while(node.next!=null){
if(node.next.val==val){
node.next = node.next.next;
}else{
node=node.next;
}
}
//考虑表头节点
return head.val==val?head.next:head;
}