剑指offer 复杂链表的复制

复杂链表的复制

题目

Leetcode 138.复制带随机指针的链表

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

方法

方法1:不采用字典

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
36
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return

pre=pHead
while pre:
tmp=pre.next
pre.next=RandomListNode(pre.label)
pre.next.next=tmp
pre=pre.next.next

pre=pHead
while pre:
if pre.random:
pre.next.random=pre.random.next
pre=pre.next.next

res=pHead.next
cur=res
pre=pHead
while pre:
pre.next=pre.next.next # 如果pre.next.next是None
if cur.next:
cur.next=cur.next.next
pre=pre.next
cur=cur.next
return res

修改最后一部分:拆分新旧链表。这比较容易理解

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return
pre=pHead
while pre:
tmp=pre.next
pre.next=RandomListNode(pre.label)
pre.next.next=tmp
pre=pre.next.next

pre=pHead
while pre:
if pre.random:
pre.next.random=pre.random.next
pre=pre.next.next

pre=pHead
res=pHead.next
cur=res
while cur.next:
pre.next=cur.next
pre=pre.next

cur.next=pre.next
cur=cur.next
pre.next=None
cur.next=None
return res
```


#### 方法2:采用字典
```python
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return pHead
copy = RandomListNode(pHead.label)
dic = {pHead: copy}
while pHead:
tcopy = dic[pHead]
if pHead.next: # 只有当pHead.next不为空才有后续操作
if pHead.next not in dic:
dic[pHead.next] = RandomListNode(pHead.next.label)
tcopy.next = dic[pHead.next]
if pHead.random:
if pHead.random not in dic:
dic[pHead.random] = RandomListNode(pHead.random.label)
tcopy.random = dic[pHead.random]
pHead = pHead.next
return copy