標籤:none solution span com enc style lis 參數 思路
題目如下:輸入一個複雜鏈表(每個節點中有節點值,以及兩個指標,一個指向下一個節點,另一個特殊指標指向任意一個節點),返回結果為複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程式會直接返回空)
思路:第一步在原鏈表的基礎上複製節點,將節點複製在原節點的後面。第二步複製隨機節點。 第三步將新舊鏈表分離。 圖示如下
代碼如下:
#encoding:utf8class RandomListNode(): def __init__(self,x): self.label = x self.next = None self.random = Noneclass Solution: def clone(pHead): if pHead == None: return None #複製節點在原節點之後 pCur = pHead while(pCur != None): node = RandomListNode(pCur.label) node.next = pCur.next pCur.next = node pCur = node.next #複製random節點 pCur = pHead while(pCur != None): if pCur.random != None: pCur.next.random = pCur.random.next pCur = pCur.next.next head = pHead.next cur = head #將新舊鏈表分離 pCur = pHead while(pCur != None): pCur.next = pCur.next.next if cur.next != None: cur.next = cur.next.next cur = cur.next pCur = pCur.next return head
python解決複雜鏈表的複製