[JZoffer]复杂链表的复制

题目描述

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

代码

# -*- 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
        head = pHead  # 将pHead复制给head
        p_head = None
        new_head = None

        random_dic = {}  # node地址与node节点对
        old_new_dic = {}  # node,head地址对

        while head:
            node = RandomListNode(head.label)  # 将head值复制给node
            node.random = head.random  # 将head.random复制给node.random
            old_new_dic[id(head)] = id(node)  #id()返回对象的内存地址,node,head地址对
            random_dic[id(node)] = node  # node地址与node节点对
            head = head.next  # head指向下一个节点

            if new_head:  # 新节点存在,
                new_head.next = node  # 将新节点的下一个节点指针指向node节点
                new_head = new_head.next  # 新节点指向它的下一个节点
            else:  # 新节点不存在
                new_head = node  # 新节点指向最初的node节点
                p_head = node  # P_head指向最初的node节点,也就是head的头节点

        new_head = p_head  # new_head指向p_head,也就是head,不过head.random为空
        while new_head:
            if new_head.random != None:
                new_head.random = random_dic[old_new_dic[id(new_head.random)]]  # new_head.random对应的node节点
            new_head = new_head.next  # new_head指针指向下一个节点
        return p_head

这个有点难理解,先mark一下。

猜你喜欢

转载自blog.csdn.net/sinat_24648637/article/details/80423492
今日推荐