复杂链表的复制python

我怕爱的太早我们不能终老 提交于 2020-03-05 18:16:36

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

思路:
  1. 遍历链表,复制每个节点,跟在每个节点后方,如A’=A.next
  2. 重新遍历链表,复制老节点的随机节点 A‘.random=A.random.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
        if not pHead:
            return None
        current_head = pHead
        #复制链表节点
        while current_head:
            clone_node = RandomListNode(current_head.label)
            clone_node.next = current_head.next
            current_head.next = clone_node
            current_head = current_head.next.next
        #复制随机节点给新链表节点
        current_head = pHead
        while current_head:
            current_head.next.random = current_head.random if current_head.random else None
            current_head = current_head.next.next
        #拆分新旧两个链表
        current_head = pHead
        clone_head = pHead.next
        while current_head:
            temp = current_head.next
            current_head.next = temp.next
            temp.next = temp.next.next if temp.next else None
            current_head = current_head.next
        return clone_head


if __name__ == "__main__":
    l1=RandomListNode(1)
    l1.next=l11=RandomListNode(3)
    l11.next=l12=RandomListNode(5)
    l12.next=l13 = RandomListNode(4)
    l11.random=RandomListNode(6)
    l12.random=RandomListNode(8)
    s=Solution()
    aa=s.Clone(l1)
    while aa:
        print(aa.label)
        aa=aa.next

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!