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
思路:
要移除一個(gè)節(jié)點(diǎn)裳扯,則需要把前一個(gè)節(jié)點(diǎn)的next指向當(dāng)前被移除節(jié)點(diǎn)的next菱肖,因此需要一個(gè)pre節(jié)點(diǎn)怀跛。
被移除的節(jié)點(diǎn)可能是head節(jié)點(diǎn)盗蟆,因此需要一個(gè)指向head的節(jié)點(diǎn)世蔗。
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return null;
}
ListNode root = new ListNode(0);
root.next = head;
ListNode pre = root;
ListNode dummy = head;
while (dummy != null) {
if (dummy.val == val) {
pre.next = dummy.next;
} else {
pre = pre.next;
}
dummy = dummy.next;
}
return root.next;
}