203. Remove Linked List Elements

https://leetcode.com/problems/remove-linked-list-elements/

solution

class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        dummy = ListNode(-1)
        dummy.next = head
        pre = dummy
        cur = dummy.next

        while cur is not None:
            if cur.val == val:
                pre.next = cur.next
                cur = cur.next
            else:
                cur = cur.next
                pre = pre.next
        return dummy.next

时间复杂度:O(n) 空间复杂度:O(1)

follow up

82. Remove Duplicates from Sorted List II

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:

        dummy = ListNode(-1, next=head)
        pre = dummy
        #cur = head
        while pre.next:
            cur = pre.next

            while cur.next and cur.val == cur.next.val:
                cur = cur.next

            if pre.next != cur:
                pre.next = cur.next
            else:
                pre = pre.next

        return dummy.next

Last updated