203. Remove Linked List Elements
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
My Solutions:
这一题要返回ListNode,所以必须要有dummy记录开头。
class Solution {
public ListNode removeElements(ListNode head, int val) {
// because we will move head, must have a dummy to return head
ListNode dummy = new ListNode(0);
dummy.next = head;
// because we will connect the element removed's before and after elements, we must do the operation on the element before it
head = dummy;
while(head.next != null) {
if (head.next.val == val) {
head.next = head.next.next; // skip the element at head.next
} else {
head = head.next;
}
}
return dummy.next;
}
}
Last updated