原创: 老表 简说Python
今日问题
"""目标:写一段程序,从无序链表中移除重复项例如:输入-> 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=