題目描述
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
解題思路
我以爲多複雜呢。。。
這種題型,一看就覺得用遞歸比較好做。只是以爲下一個節點是RandomListNode類型,特殊指針指向的也是RandomListNode類型的;按照這種想法寫出的代碼:
Python代碼(Wrong)
def Clone(self, pHead):
if not pHead:
return None
cloneHead = RandomListNode(pHead.label)
cloneHead.random = self.Clone(pHead.random)
cloneHead.next = self.Clone(pHead.next)
return cloneHead
結果牛客網提示說:
maximum recursion depth exceeded
原來只有下一個節點是RandomListNode類型的,特殊指針指向的節點是普通節點… 還以爲這個RandomListNode是一張網,結果只是有分叉的一根繩…
Python代碼(Right)
def Clone(self, pHead):
if not pHead:
return None
cloneHead = RandomListNode(pHead.label)
cloneHead.random = pHead.random
cloneHead.next = self.Clone(pHead.next)
return cloneHead