题目:
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
解答:
遍历整个链表,找到相应节点删除即可,但要注意各种特殊情况的处理。
如当第一个节点就是待删除节点时,要进行单独的操作。
class Solution {
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
ListNode node = head;
while(node != null && node.next != null) {
if (node.next.val == val) {
node.next = node.next.next;
} else {
node = node.next;
}
}
return head;
}
}
要注意每个节点都是需独立判断的。在之前的提交中,忽略了两个连续待删节点的情况,导致判断错误,漏掉了第二个待删节点。