复杂链表的复制

复杂链表的复制

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路

  • 解法一
    链表。
    通过在链表每个节点后插入copyNode完成复杂链表的复制。
    主要分为三个步骤:
  1. 遍历链表,在每个节点后插入copyNode
  2. 遍历链表,设置copyNode.random = Node.random.next实现
  3. 遍历链表,将链表拆分为原链表和复制链表两个部分。用原链表来控制循环。当原链表遍历到尾节点时,显然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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值