算法
(模拟) $O(n)$
用一个 dummy
节点指向头节点,维护一个 cur
节点,每当他下一个节点为要删除的数时,删除下一个节点,直到当前节点为最后一个节点。
C++ 代码
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy;
dummy.next = head;
head = &dummy;
while (head->next != NULL) {
if (head->next->val == val) {
head->next = head->next->next;
} else {
head = head->next;
}
}
return dummy.next;
}
};
Java 代码
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) cur.next = cur.next.next;
else cur = cur.next;
}
return dummy.next;
}
}
Python 代码
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next