题目描述

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

思路:

有两个指针与一个值。

在复制该链表之前,首先初始化一个链表


# -*- coding:utf-8 -*-
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

然后依次比较

label
next
random

是否唯空
弱不为空,将指复制给该指针

class
Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here if pHead == None: return None res = RandomListNode(0) firstNode = res while pHead != None: temp = RandomListNode(pHead.label) res.label = temp.label if pHead.random != None: res.random = RandomListNode(pHead.random.label) else: res.random = None if pHead.next != None: res.next = RandomListNode(pHead.next.label) else: res.next = None res = res.next pHead = pHead.next return firstNode

 

相关文章:

  • 2022-12-23
  • 2021-08-16
  • 2021-06-28
  • 2021-04-10
  • 2021-11-19
猜你喜欢
  • 2021-11-28
  • 2021-05-27
  • 2021-11-21
  • 2022-02-11
  • 2022-01-07
  • 2021-07-29
  • 2021-06-26
相关资源
相似解决方案