题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
- 遍历链表,复制每个节点,跟在每个节点后方,如A’=A.next
- 重新遍历链表,复制老节点的随机节点 A‘.random=A.random.next
- 拆分链表,将链表拆分成原链表和复制后的链表
# -*- 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
来源:CSDN
作者:程序媛的攻城之路
链接:https://blog.csdn.net/weixin_32825997/article/details/104671731