知识点:链表
题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
对于复杂链表的复制,如果头节点为空,返回None。使用递归法新建一个链表newNode,newNode的值为pHead的label的值,newNode的next指针递归,newNode的随机值指向pHead的random值。
代码实现:(递归法)
# -*- 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
#构造一个新链表
newNode=RandomListNode(pHead.label)
newNode.next=self.Clone(pHead.next)
newNode.random=pHead.random
return newNode
代码测试:
# -*- coding:utf-8 -*-
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
def Clone(self, head):
if not head:
return None
newNode = RandomListNode(head.label)
newNode.next = self.Clone(head.next)
newNode.random = head.random
#return newNode
print(newNode.label)
s = Solution()
node1=RandomListNode(5)
node2=RandomListNode(7)
node3=RandomListNode(8)
node4=RandomListNode(9)
node1.next=node2
node2.next=node3
node3.next=node4
node1.random=node3
node2.random=node4
node3.random=node2
node4.random=node1
res = s.Clone(node1)
运行结果:
参考链接:
https://blog.csdn.net/qq_36936730/article/details/104668362