83. 删除排序链表中的重复元素

83. 删除排序链表中的重复元素

思路

其实和数组去重是一模一样的,唯一的区别是把数组赋值操作变成操作指针而已。

参考

代码

Python

# 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]:
        if head is None:
            return None
        
        slow = head
        fast = head

        while fast is not None:
            if fast.val != slow.val:
                # nums[slow] = nums[fast]
                slow.next = fast
                # slow = slow + 1
                slow = slow.next
            # fast = fast + 1
            fast = fast.next

        # 断开与后面重复元素的连接
        slow.next = None
        return head
posted @ 2026-07-24 16:31  wyzsgy  阅读(3)  评论(0)    收藏  举报