删除有序链表中的重复元素(python)

重复的留下一个
def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        #空链表
        if head == None:
            return None
        #遍历指针
        cur = head
        #指针当前和下一位不为空
        while cur and cur.next:
            #如果当前与下一位相等则忽略下一位
            if(cur.val == cur.next.val): 
                cur.next = cur.next.next
            #否则指针正常遍历
            else:
                cur = cur.next
        return head
 
重复的不留
def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        #空链表
        if head == None:
            return None
        res = ListNode(0)
        #在链表前加一个表头
        res.next = head
        cur = res
        while cur.next and cur.next.next:
            #遇到相邻两个节点值相同
            if cur.next.val == cur.next.next.val:
                temp = cur.next.val
                #将所有相同的都跳过
                while cur.next != None and cur.next.val == temp:
                    cur.next = cur.next.next
            else:
                cur = cur.next
        #返回时去掉表头
        return res.next
posted @   小仙女、  阅读(156)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示