获取节点索引 | #复杂链表的复制#

复杂链表的复制

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=265&tqId=39237&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=undefined&tags=&title=

# -*- 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:
            my_pHead = RandomListNode(pHead.label)
            my_cur_node = my_pHead
            cur_node = pHead
            node_len = 1
            while cur_node.next:
                cur_node = cur_node.next
                # print(cur_node.label)
                my_cur_node.next = RandomListNode(cur_node.label)
                my_cur_node = my_cur_node.next
                node_len += 1

            my_cur_node = my_pHead
            cur_node = pHead
            while cur_node:
                # print(cur_node.label)
                rnd_node = cur_node.random
                if not rnd_node:
                    my_cur_node.random = None
                    cur_node = cur_node.next
                    my_cur_node = my_cur_node.next
                    continue
                rnd_cnt = 0
                my_rnd_node = my_pHead
                while rnd_node and rnd_node.next:  # 取得random指向节点的倒序索引
                    rnd_node = rnd_node.next
                    rnd_cnt += 1
                # print(rnd_cnt)
                rnd_idx = node_len-1-rnd_cnt  # 取得random节点的正序索引
                # print(rnd_idx)
                while rnd_idx > 0:  # 根据正序索引建立复制链表的random链接
                    my_rnd_node = my_rnd_node.next
                    rnd_idx -= 1
                # print(my_cur_node.label, my_rnd_node.label)
                my_cur_node.random = my_rnd_node
                cur_node = cur_node.next
                my_cur_node = my_cur_node.next
            return my_pHead
        else:
            return None

如上,该题的关键在于获取random节点的索引,然后根据索引建立复制品的random链接

全部评论

相关推荐

希望各位大哥分享一下自己的看法,对于机器人行业确实不太了解
绝顶但不聪明:如果是机器人相关岗位,优先优必选(专门***器人的),其他岗位选小米
投递小米集团等公司10个岗位 > 牛客解忧铺 牛客在线求职答疑中心
点赞 评论 收藏
分享
11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务