【LeetCode with Python】 Copy List with Random Pointer

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/copy-list-with-random-pointer/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/39453281


A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.


# Definition for singly-linked list with a random pointer.
class RandomListNode:
    def __init__(self, x):
        self.label = x
        self.next = None
        self.random = None

class Solution:
    # @param head, a RandomListNode
    # @return a RandomListNode
    def copyRandomList(self, head):
        if None == head:
            return None
        save_list = [ ]
        p1 = head
        while None != p1:
            save_list.append(p1)
            p1 = p1.next
        new_head = RandomListNode(-1)
        new_head.next = head
        first = new_head
        second = head
        copy_head = RandomListNode(-1)
        copy_first = copy_head
        copy_second = None
        while None != first:
            copy_second = RandomListNode(second.label) if None != second else None
            copy_first.next = copy_second
            copy_first = copy_first.next
            first = first.next
            if None != second:
                second = second.next

        p1 = head
        p1_tail = head.next
        p2 = copy_head.next
        while None != p1:
            p1_tail = p1.next
            p1.next = p2
            p2.random = p1
            p1 = p1_tail
            p2 = p2.next
        p2 = copy_head.next
        #p1 = head
        while None != p2:
            p2.random = p2.random.random.next if None != p2.random.random else None
            #p1.next = p1.next.next.random if None != p1.next.next else None   # may broken the previous p1.next, so have to save ori list
            p2 = p2.next
            #p1 = p1.next
        len_save_list = len(save_list)
        for i in range(0, len_save_list - 1):
            save_list[i].next = save_list[i + 1]
        save_list[len_save_list - 1].next = None
        return copy_head.next

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值