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
'LeetCode > Problems' 카테고리의 다른 글
LeetCode 561. Array Partition I [Easy] (0) | 2020.08.26 |
---|---|
LeetCode 15. 3Sum [Medium] (0) | 2020.08.25 |
LeetCode 42. Trapping Rain Water [Hard] (1) | 2020.08.24 |
LeetCode 49. Group Anagrams (0) | 2020.08.19 |
LeetCode 819. Most Common Word (0) | 2020.08.18 |
댓글