Skip to content

Latest commit

 

History

History
46 lines (34 loc) · 1.04 KB

0083. Remove Duplicates from Sorted List.md

File metadata and controls

46 lines (34 loc) · 1.04 KB

题目

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

我的思路

直接遍历链表,依次判断即可。注意在指针后移之前,要先判断当前的val和next.val是否相等,不相等才能后移,否则不能处理连续2个以上的duplicates。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        l = head
        while l:
            if not l.next:
                return head
            
            if l.val == l.next.val:
                if not l.next.next:
                    l.next = None
                    return head
                l.next = l.next.next
                
            if l.val != l.next.val:
                l = l.next