剑指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