Skip to content

Commit e192c6c

Browse files
committed
复制带随机指针的链表
1 parent a9ad8cd commit e192c6c

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

copy_list_with_random_pointer.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param head: A RandomListNode
5+
# @return: A RandomListNode
6+
def copyRandomList(self, head):
7+
# write your code here
8+
'''
9+
思路如下,abcd...代表原链表,a'b'c'd'...代表新链表。()内代表random,'/'代表None。
10+
初始状态:a(d)->b(/)->c(e)->d(a)
11+
1. 插入并复制原来的random节点:a(d)->a'(d)->b(/)->b'(/)->c(e)->c'(e)->d(a)->d'(a)
12+
2. 更新新节点的random(因为x指向x'):a(d)->a'(d')->b(/)->b'(/)->c(e)->c'(e')->d(a)->d'(a')
13+
3. 拆成两条链表并返回
14+
'''
15+
if not head:
16+
return None
17+
node = head
18+
while node:
19+
new_node = RandomListNode(node.label)
20+
new_node.next, new_node.random = node.next, node.random
21+
node.next = new_node
22+
node = new_node.next
23+
node = head.next
24+
while node:
25+
node.random = node.random.next
26+
node = node.next # 向前两步
27+
node = node.next
28+
new_head, new_tail = None, None
29+
node = head
30+
while node:
31+
prev = node
32+
node = node.next
33+
prev.next = node.next # prev.next保存下一个node的位置
34+
if not new_head:
35+
new_node = node
36+
else:
37+
new_tail.next = node
38+
new_tail = node
39+
new_tail.next = None
40+
node = prev.next
41+
return new_head

0 commit comments

Comments
 (0)