剑指offer-复杂链表的复制-链表-python

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的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

 

posted @ 2019-12-09 09:53  ayew  阅读(141)  评论(0编辑  收藏  举报