Leetcode # 203. Remove Linked List Elements
https://leetcode.com/problems/remove-linked-list-elements/
Solution 1
class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: new_head = head while new_head is not None and new_head.val == val: new_head = new_head.next cur = new_head while cur: while cur.next is not None and cur.next.val == val: cur.next = cur.next.next cur = cur.next return new_head
注意事項
- new_head其值是否為val
- 當跳過某一個值為val的node時,下一個node是否其值也為val
Solution 2
Time Complexity: O(len(linked_list))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
注意:
root = ListNode(0, head)
pre, cur = root, head
root, pre, cur = ListNode(0, head), root, head
由於多重賦值是先計算右側,所以會有 root 尚未宣告的 error
class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: root = ListNode(0, head) pre, cur = root, head while cur: if cur.val == val: while cur and cur.val == val: cur = cur.next pre.next = cur else: pre, cur = cur, cur.next return root.next
Last Updated on 2024/06/08 by A1go