# -*- 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 not pHead:
return None
newnode=RandomListNode(pHead.label)
newnode.random=pHead.random
newnode.next=self.Clone(pHead.next)
return newnode
"""
if not pHead:
return None
cur=pHead
#在原链表中插入一个与前面元素相同的node
"""
1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
2、遍历链表,A1->random = A->random->next;
3、将链表拆分成原链表和复制后的链表
"""
while cur:
tmp = RandomListNode(cur.label)
tmp.next = cur.next
cur.next = tmp
cur = tmp.next
cur = pHead
while cur:
tmp=cur.next
if cur.random:
tmp.random=cur.random.next
cur=tmp.next
cur=pHead
res=pHead.next
while cur.next:
tmp=cur.next
cur.next=tmp.next
cur=tmp
return res
剑指offer-复杂链表的复制(python)
最新推荐文章于 2022-04-30 20:20:41 发布