Scribbling

LeetCode: 82. Remove Duplicates from Sorted List II 본문

Computer Science/Coding Test

LeetCode: 82. Remove Duplicates from Sorted List II

focalpoint 2021. 10. 6. 16:09
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return None
        
        new_head = ListNode()
        ptr = new_head
        reg, freq = head.val, 0
        cur = head
        while cur != None:
            if reg != cur.val:
                if freq == 1:
                    temp = ListNode(reg)
                    ptr.next = temp
                    ptr = temp
                reg = cur.val
                freq = 1
            else:
                freq += 1
            cur = cur.next
        if freq == 1:
            ptr.next = ListNode(reg)
        return new_head.next