1. 程式人生 > >劍指offer24.複雜連結串列的複製

劍指offer24.複雜連結串列的複製

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