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
浙公网安备 33010602011771号