db2删除完全相同的重复数据_Smaller And Smarter Python数据结构:删除无序链表重复结点...

原创: 老表 简说Python

0ce9032391e39b7bf8d909474a3e53f7.png

今日问题

"""目标:写一段程序,从无序链表中移除重复项例如:输入-> 1->0->3->1->4->5->1->8输出-> 1->0->3->4->5->8""""""Goal: write a program to remove duplicates from the unordered listFor example:Input - > 1 - > 0 - > 3 - > 1 - > 4 - > 5 - > 1 - > 8Output - > 1 - > 0 - > 3 - > 4 - > 5 - > 8"""

首先我们写好链表的基本操作,在a_0_base.py文件中,目前包含对链表的定义类,初始化函数,遍历函数。(带头结点)

# -*- coding: utf-8 -*-"""@author = 老表@date = 2019-10-19@个人微信公众号 : 简说Python"""# 链表数据结构定义class ListNode: def __init__(self, x): self.data = x self.next = Noneclass ListOperation: # 根据链表数据初始化链表 @staticmethod def init_list(n_list): # 初始化一个头指针 head = ListNode("head") cur = head for i in n_list: node = ListNode(i) cur.next = node cur = node # 相当于 cur = cur.next,后移 return head # 遍历链表 @staticmethod def ergodic_list(head): cur = head.next while cur: print(cur.data) cur = cur.next

解题

开始程序前需提前导入前面写好的链表基本操作包a_0_base。

from Linked_list.a_0_base import ListOperation

方法一:递归去重

"""Method One : 递归去重核心思想:每次遍历去重前,都先对子链表进行去重处理,这样去重的子链表都会产生一个子链表,直到递归到尾结点,此时开始回溯,每次回溯,会完成一个子链的去重,直到回溯到头结点,链表去重完成。时间复杂度:O(N^2)空间复杂度:O(1)"""

代码

def remove_duplicates_one(head): """ :type head: ListNode :rtype: ListNode """ if not head.next: # 空链表或者遍历到最后一个结点 return head # 返回头结点或者开始回溯 cur_node = head # 记录头结点 head.next = remove_duplicates_one(head.next) # 递归,往后遍历 # print("此时cur_node=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值