复杂链表的复制 (剑指offer)(复制带随机指针的链表)python

剑指offer面试题35:给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的深拷贝。
leetcode:138. 复制带随机指针的链表 【https://leetcode-cn.com/problems/copy-list-with-random-pointer/

这道题的解题思路比较多,这里仅实现比较巧妙的一种。第一,我们先把原链表中的每个节点都复制一下,并且将复制的节点连接在原节点之后。第二,我们把每个原节点上的随即指针复制给复制的节点一份;最后,将这个链表拆分为原有链表和复制出来的链表两个部分,并返回我们复制出的链表头。
代码如下:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None
        #copy every node on the original linklist, and attach it after the node
        cur = head
        while cur:
            cur_next = cur.next
            clone = Node(cur.val, None, None)
            cur.next = clone
            clone.next = cur_next
            cur = cur_next
        
        #copy random pointer of each node
        cur = head
        while cur:
            if cur.random:
                cur.next.random = cur.random.next
            cur = cur.next.next
            
        #deattach copyed nodes from the original linkedlist
        cur = head
        clone_head = head.next
        clone_cur = clone_head
        while clone_cur.next:
            cur.next = cur.next.next
            cur = cur.next
            clone_cur.next = clone_cur.next.next
            clone_cur = clone_cur.next
        #set tail pointer point to None
        cur.next = None
        clone_cur.next = None
        return clone_head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值