复杂链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路
- 解法一
链表。
通过在链表每个节点后插入copyNode完成复杂链表的复制。
主要分为三个步骤:
- 遍历链表,在每个节点后插入copyNode
- 遍历链表,设置copyNode.random = Node.random.next实现
- 遍历链表,将链表拆分为原链表和复制链表两个部分。用原链表来控制循环。当原链表遍历到尾节点时,显然copyNode.next为空。
如图所示:
- 解法二
词典
创建node与copyNode的词典映射。对词典进行遍历,设置copyNode.next和copyNode.random.
代码
- 解法一
# -*- 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 is None:
return
cur = pHead
while cur is not None:
copyNode = RandomListNode(cur.label)
temp = cur.next
cur.next = copyNode
copyNode.next = temp
cur = temp
cur = pHead
while cur is not None:
if cur.random is not None:
cur.next.random = cur.random.next
cur = cur.next.next
newHead = pHead.next
oldCur,newCur = pHead,pHead.next
while oldCur is not None:
oldCur.next = oldCur.next.next
if newCur.next is not None:
newCur.next = newCur.next.next
oldCur = oldCur.next
newCur = newCur.next
return newHead
- 解法二
copyDict,cur = {},pHead
while cur != None: #创建节点-新节点的映射copyDict
copyDict[cur] = RandomListNode(cur.label)
cur = cur.next
for i in copyDict.keys():
copyDict[i].next = i.next
copyDict[i].random = i.random
return copyDict[pHead]