6/04/2020

[LeetCode] 83. Remove Duplicates from Sorted List

Problem : https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Traverse the input linked list and add node to output linked list if its value is encountered at the first time.

# 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: ListNode) -> ListNode:
        dummy = None
        p1 = dummy
        p2 = head
        
        while p2:
            if not p1:
                dummy = p2
                p1 = dummy
            elif p1.val != p2.val:
                p1.next = p2
                p1 = p1.next
            
            p2 = p2.next
        
        # end the output linked list
        if p1:
            p1.next = None
        
        return dummy

No comments:

Post a Comment