diff --git "a/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" "b/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" index 5a4bbb7423..65f7681549 100644 --- "a/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" +++ "b/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" @@ -369,9 +369,31 @@ class Solution { ``` ### Python: +使用原鏈表操作: +```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]: + # 刪除頭節點 + while head is not None and head.val == val: + head = head.next + + cur = head + # 刪除非頭節點 + while head is not None and cur.next: + if cur.next.val == val: + cur.next = cur.next.next + else: + cur = cur.next + return head +``` +設置虛擬頭節點: ```python -(版本一)虚拟头节点法 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None):