mengyushi / LeetCode

4 stars 0 forks source link

203. Remove Linked List Elements #263

Open mengyushi opened 4 years ago

mengyushi commented 4 years ago
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        '''
        1->2->6->3->4->5->6->None, val = 6
                      pre p p.next

        pre.next = p.next if p.val = val

        dummy head

        Time Complexity: O(N)
        Space Complexity: O(1)

        '''
        dummy = ListNode(None)
        dummy.next = head

        pre, p = dummy, head

        while p:
            if p.val == val:
                pre.next = p.next
            else:
                pre = p
            p = p.next

        return dummy.next