剑指offer24.复杂链表的复制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/86234814

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&tPage=2&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

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

首先想到的肯定是递归来求解了:

# -*- 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 pHead == None:
            return None
        res = RandomListNode(pHead.label)
        res.random = pHead.random
        res.next = self.Clone(pHead.next)
        return res

还一种思路是复制+复制+拆分:
在这里插入图片描述

# -*- 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 pHead == None:
            return None

        head = pHead
        while head:
            tmp = head.next
            head.next = RandomListNode(head.label)
            head.next.next = tmp
            head = tmp

        head = pHead
        while head:
            copy_node = head.next
            next_head = copy_node.next
            if head.random:
                copy_node.random = head.random.next
            head = next_head

        head = pHead
        res = pHead.next
        while head:
            copy_node = head.next
            next_head = copy_node.next
            head.next = next_head
            if next_head:
                copy_node.next = next_head.next
            else:
                copy_node.next = None
            head = next_head
        return res

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/86234814