LeetCode/Problems

Leet Code 83. Remove Duplicates from Sorted List [Easy]

벤진[Benzene] 2020. 9. 8. 06:44

Problem:

Given a sorted linked list, delete all duplicates such that each element appear only once.

 

Example 1:

Input: 1->1->2

Output: 1->2

 

Example 2:

Input: 1->1->2->3->3

Output: 1->2->3

 

-Summary-

1. Set root as head first.

2. Move the head and compare the current value with the next value. If it is the same, point next to next.next. Otherwise, move head to the next.

3. Return root

 

-Code-

# 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:
        
        root = head
        
        while head and head.next:
            if head.val == head.next.val:
                head.next = head.next.next
            else:    
                head = head.next

        return root