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
需要考虑第一位可能就是要删除的元素以及可能有连续多位要删除的元素,比如6 -> 1 -> 6 -> 6 -> 2, val = 6
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = head;
while (head != null) {
if (head.val == val) {
pre.next = head.next;
head = head.next;
continue;
}
pre = head;
head = head.next;
}
return dummy.next;
}