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

复杂链表的复制

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链接

全部评论

相关推荐

11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务