CODE/Algorithms & Data Structures

[Coderust] Remove Duplicates from a Linked List

BoriTea 2022. 3. 10. 15:50

 

 

Problem

 

 


 

Solution

 

 

# 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 or not head.next:
            return head
        
        curr = head
        n = head.next
        
        while True:
            if curr.val != n.val:
                curr.next = n
                curr = curr.next
            n = n.next
            if not n:
                curr.next = None
                break
            
        return head

 

Time Complexity

O(N)

 

 

Space Complexity

O(1)