[LeetCode]138 复制带随机指针的链表

题目描述

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深度拷贝。

思路

  • 在每个节点后插入复制节点 new_node,构成新链表
  • 给出每个复制节点的 random 指向
  • 拆分链表

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None

class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return None
cur_head = head
while cur_head:
label = cur_head.label
new_node = RandomListNode(label)
new_node.next = cur_head.next
cur_head.next = new_node
cur_head = new_node.next
cur_head = head
while cur_head:
new_node = cur_head.next
if cur_head.random:
new_node.random = cur_head.random.next
cur_head = new_node.next
cur_head = head
new_head = head.next
while cur_head is not None and cur_head.next:
next_node = cur_head.next
cur_head.next = next_node.next
cur_head = next_node
return new_head