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

此博客介绍了如何编写Python代码实现删除排序链表中的重复元素。具体解题思路是通过遍历链表,当遇到相同值的连续节点时,跳过这些重复节点,从而达到删除目的。示例中给出了代码执行过程的详细步骤,并提供了完整的程序代码实现。
摘要由CSDN通过智能技术生成

f20428a09e174ba397fc9a44eab3eccc.png

解题思路与官方提供的一致,即遍历。但此处主要记录每次操作指针的走向

以【1,1,2,2,3】 为例

class Solution:
    def deleteDuplicates(self,head):
        if not head:
            return head
        # if head == None:
        #     return head
        cur = head
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head

(1)未进入循环:

02943c01ae054edabb0b4051d259f01c.png

(2)第一次循环,且执行 if cur.val == cur.next.val 的判断

fa0baaa6a8dd4f648d319f2327344372.png

 cc2f9e6cfc5e4e3395d850286f9809fb.png

 (3)第2次循环,且执行else的操作

89ac3eceb58341bd951c5f70957c3a19.png

 (4)第3次循环,且执行 if cur.val == cur.next.val 的判断

e06500653b9a4d3b994a8055984fb87d.png

da8931b273ca4ad48ad79077ecc31d1d.png

 (5)第4次循环,且执行else的操作

 7b981a000eae4682bd61b2b5f3add749.png

完整程序

"""
力扣题 :83.删除排序链表中的重复元素
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/


"""

class ListNode:
    def __init__(self,val=0,next = None):
        self.val = val
        self.next = next


class Solution:
    def deleteDuplicates(self,head):
        if not head:
            return head
        # if head == None:
        #     return head
        cur = head
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head

arr = [1,1,2,2,3]
# arr=[]
pre = ListNode(0)
cur = pre
for j in range(len(arr)):
    node = ListNode(arr[j])
    cur.next = node
    cur = cur.next

l2 = Solution().deleteDuplicates(pre.next)
while l2:
    print(l2.val,end='')
    l2 = l2.next




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值