題目描述
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
解題思路:時間複雜度O(n)
參考地址 https://www.cnblogs.com/clouds-114/p/8733558.html
第一步在原鏈表的基礎上覆制節點,將節點複製在原節點的後面。
第二步複製隨機節點。
第三步將新舊鏈表分離。
# -*- 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
#複製節點在原節點之後
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