题目
复制带有随机指针的链表:一个单链表除了next指针外还有一个random指针随机指向任何一个元素(可能为空)
《剑指offer》上的面试题26
分析
方法一:
map<旧地址,新地址>,先按普通方法复制链表,再两个链表同时走复制random(旧节点a,新节点a’)a'->random=map[a->random]
(空指针单独处理)
方法二:
插入:每个节点后面插入一个自身的“复本”
复制random指针:一个旧节点a的复本是a->next, a->random的复本是a->random->next,新节点的random指针a->next->random = a->random->next(空指针单独处理)
拆分:旧节点链表是奇数项,新节点链表是偶数项。
方法二代码
- 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
- 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