Solution 1
比较简单的一道题,需要两个过程:目标元素的判定和对应元素的移除,这在过去的题目中都有涉及。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入链表的元素个数,线性遍历一次
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummyHead = new ListNode(0, head);
ListNode *prev = dummyHead, *now = head;
while (now != nullptr) {
if (now->val == val) {
prev->next = now->next;
} else {
prev = prev->next;
}
now = now->next;
}
return dummyHead->next;
}
};
Solution 2
Solution 1的Python实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummyHead = ListNode(0, head)
prev, now = dummyHead, head
while now is not None:
if now.val == val:
prev.next = now.next
else:
prev = prev.next
now = now.next
return dummyHead.next