题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
法1:递归法
# -*- coding:utf-8 -*- class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here if not pHead: return newnode=RandomListNode(pHead.label) newnode.random=pHead.random newnode.next=self.clone(pHead.next) return newnode
时间复杂度O(n^2),每一个节点的random指针需要从头遍历。
黄色部分为什么这么写不理解。
法二:哈希表
# -*- coding:utf-8 -*- class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here nodelist = [] randomlist = [] labellist = [] while pHead: nodelist.append(pHead) randomlist.append(pHead.random) labellist.append(pHead.label) pHead = pHead.next labelIndexlist = map(lambda c: nodelist.index(c) if c else -1, randomlist) copy = RandomListNode(0) pre = copy nodelist = map(lambda c: RandomListNode(c), labellist) for i in range(len(nodelist)): if labelIndexlist[i] != -1: nodelist[i].random = nodelist[labelIndexlist[i]] for i in nodelist: pre.next = i pre = pre.next return copy.next
黄色部分疑问同法1,绿色部分也有疑问?
ps:1:map()函数
map(function, iterable, ...)
第二个参数序列的每一个元素调用第一个参数(函数)。
2:lambda 匿名函数
冒号:前为输入参数,:后为函数体