83 删除排序链表中的重复元素I,II

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

在这里插入图片描述

1.双指针,注意边界,链表为[]不存在head.next

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None:
            return head
        s,f=head,head.next
        while f:
            if s.val!=f.val:
                s=s.next
                f=f.next
            else:
                f=f.next
                s.next=f
        return head

2.递归

递归讲解
①停止条件:只剩一个元素或空,head,head.next==None
②等价关系:deleteDuplicates(head)=deleteDuplicates(head.next)+检查head与head.next是否相等

class Solution(object):
    def deleteDuplicates(self, head):
        if head==None or head.next==None:
            return head
        ###每一次递归指向已经去重的序列###
        head.next=self.deleteDuplicates(head.next)
        if head.val==head.next.val:
            head=head.next
        '''另一种写法:
        tmp = self.deleteDuplicates(head.next)
        #if not tmp:
        #    return head
        head.next = tmp.next if head.val == tmp.val else tmp
		'''
        return head
        

删除链表中的重复元素II

在这里插入图片描述
cur指针从哑节点开始
判断cur.next与cur.next.next是否同值
储存该值,并不断向后判断值取到不同值时停止
若不同则更新cur,cur=cur.next

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head is None:return head
        dummy=ListNode(next=head)
        cur=dummy
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                x = cur.next.val
                while cur.next and cur.next.val == x:
                    cur.next = cur.next.next
            else:
                cur=cur.next
        return dummy.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值