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
思路:
要移除一個節(jié)點,則需要把前一個節(jié)點的next指向當(dāng)前被移除節(jié)點的next,因此需要一個pre節(jié)點。
被移除的節(jié)點可能是head節(jié)點,因此需要一個指向head的節(jié)點。
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;
}