题解 | #复杂链表的复制#

复杂链表的复制

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba

# -*- 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 pHead
        p = pHead
        p3 = p2 = RandomListNode(p.label)
        p = p.next
        while p is not None:
            p2.next = RandomListNode(p.label)
            p = p.next
            p2 = p2.next
        if p is None:
            p2.next = None

        p4 = p2 = p3
        p = pHead
        while p is not None:
            r = p.random
            if r is not None:
                while p2 is not None and p2.label != r.label:
                    p2 = p2.next
                if p2 is not None and p2.label == r.label:
                    p3.random = p2
            p3 = p3.next
            p2 = p4
            p = p.next
        return p4

第一步复制链表的next。

第二步复制链表的random。

注意:

  1. 第二步只有在第一步的基础上才能执行。
  2. 第二步需要从复制后的链表的头依次对比label是否相等。
全部评论

相关推荐

粗心的熊熊求求offer:什么内容都没有还弄两页
点赞 评论 收藏
分享
湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
06-27 15:29
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务