复杂链表的复制

题目

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

代码实现

 1 # -*- coding:utf-8 -*-
 2 # class RandomListNode:
 3 #     def __init__(self, x):
 4 #         self.label = x
 5 #         self.next = None
 6 #         self.random = None
 7 class Solution:
 8     # 返回 RandomListNode
 9     def Clone(self, pHead):
10         # write code here
11         if not pHead:
12             return None
13         # 复制节点,连接next
14         pNode = pHead
15         while pNode:
16             pClone = RandomListNode(pNode.label) #创建新的链表节点 
17             pClone.next = pNode.next
18             pNode.next= pClone
19             pNode = pClone.next
20         
21         # 连接random指针
22         pNode = pHead
23         while pNode:
24             node = pNode.next # 指向复制的节点
25             if pNode.random: #任意指针可能为空
26                 node.random=pNode.random.next
27             pNode = node.next
28         
29         #拆分链表
30         pphead = pHead
31         pHeadClone = pHead.next
32         while pphead:
33             temp = pphead.next
34             ppheadnext= temp.next
35             pphead.next = ppheadnext
36             if ppheadnext: # 要判断一下是否为空 
37                 temp.next = ppheadnext.next
38             else:
39                 temp.next=None #处理表尾
40             pphead=pphead.next
41         return pHeadClone
42             
43         
44         
45         
46         

注意的点

1.使用Python创建一个新节点

2.对复制后的表尾的处理

原文地址:https://www.cnblogs.com/shuangcao/p/12767533.html