剑指offer 面试题35 python版+解析:复杂链表的复制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mabozi08/article/details/88846197

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

思路

1. 根据原始链表的每个节点N创建对应的N‘,把N’链接到N的后面

2. 设置复制出来的节点random。N‘是N的Next指向的节点,同意S’也是S的Next指向的节点。

3. 把这个长链表拆分成两个链表。

# -*- 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
        # 复制链表,组合成一个长链表
        pNode = pHead
        while pNode:
            clone_node = RandomListNode(pNode.label)
            clone_node.next = pNode.next
            clone_node.random = None
            
            pNode.next = clone_node
            pNode = clone_node.next
            
        #复制random
        pNode = pHead
        while pNode:
            clone_node = pNode.next
            if pNode.random:
                clone_node.random = pNode.random.next
            pNode = clone_node.next
        
        #拆分长列表
        pNode = pHead
        clone_head = None
        clone_node = None
        if pNode:
            clone_head = clone_node = pNode.next
            pNode.next = clone_node.next
            pNode = clone_node.next
        while pNode:
            clone_node.next = pNode.next
            clone_node = clone_node.next
            pNode.next = clone_node.next
            pNode = clone_node.next
        return clone_head

猜你喜欢

转载自blog.csdn.net/mabozi08/article/details/88846197
今日推荐