[剑指Offer]复杂链表的复制[Python]

题目要求:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

解题思路:一开始都没看懂题,后来看了大家的评论才知道复杂链表的复制是咋回事.思路就是先遍历链表,把next的节点都复制好,然后再查看每个节点的random指向哪里了,就让新链表的random也指向哪里

class Solution:
    # 返回 RandomListNode
    def CloneNext(self,root):
        if root:
            cHead = RandomListNode(root.label)
            cHead.next = self.CloneNext(root.next)
            return cHead
    def Clone(self, pHead):
        # write code here
        if pHead:
            cHead = self.CloneNext(pHead)
            pList = []
            cList = []
            while pHead:
                pList.append(pHead)
                cList.append(cHead)
                pHead = pHead.next
                cHead = cHead.next
            for i in range(len(pList)):
                if pList[i].random:
                    index = pList.index(pList[i].random)
                    cList[i].random = cList[index]
            return cList[0]

猜你喜欢

转载自blog.csdn.net/jillian_sea/article/details/80350883