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

Problem: 82. 删除排序链表中的重复元素 II

思路

遍历

解题方法

这题最大的特点就是要删除所有重复的元素

因为涉及到头节点是重复元素的情况,所以需要设置一个虚拟的头结点dummy

利用cur代表当前位置的指针

if cur.next.val == cur.next.next.val:
    # 需要删除所有重复的元素,这里用tem指向cur.next
    tem = cur.next
    # 不断判断tem.val与tem.next.val的关系,然后删除所有重复的元素
    while tem.val == tem.next.val:
        tem = tem.next # 此时cur还在原地
    cur.next = tem.next # 指向tem的下一个位置
else:
    cur = cur.next

复杂度

时间复杂度: O ( n ) O(n) O(n)

空间复杂度: O ( 1 ) O(1) O(1)

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: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(val=-1, next=head) # 虚拟节点
        cur = dummy
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                tem = cur.next
                while tem.next and tem.val == tem.next.val:
                    tem = tem.next
                cur.next = tem.next
            else:
                cur = cur.next
        return dummy.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aJupyter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值