【題目描述】輸入一個復雜鏈表(每個節(jié)點中有節(jié)點值,以及兩個指針,一個指向下一個節(jié)點,另一個特殊指針指向任意一個節(jié)點),返回結果為復制后復雜鏈表的head。(注意,輸出結果中請不要返回參數(shù)中的節(jié)點引用,否則判題程序會直接返回空)
【思路】
1.鏈表復制
2.鏈表兄弟節(jié)點復制
3.鏈表奇偶分離

image.png
代碼:
# 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 pHead
curNode = pHead
#復制鏈表
while curNode!=None:
newNode = RandomListNode(curNode.label)
newNode.next = curNode.next
curNode.next = newNode
curNode = newNode.next
#復制兄弟節(jié)點
curNode = pHead
while curNode!=None:
if curNode.random!=None:
curNode.next.random = curNode.random.next
curNode = curNode.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