[Leetcode 83] Remove Duplicated From Sorted List

이재윤·2025년 2월 11일
0

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

1) 코드

# 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]:
        
        res = ListNode(0, head)

        while head and head.next:
            if head.val == head.next.val:
                head.next = head.next.next
            else:
                head = head.next

        return res.next

2) 해설

  • 현재 위치와 다음 위치의 값이 같을 때,
    현재 위치의 다음 노드를, 다음 다음 노드로 교체해주면 된다
    -> 이 때, 주의할 점은 if 문에서 true가 되면 계속해서 해주고,
    false일 때만 head를 옮겨줘야 한다는 점이다.

0개의 댓글