【LeetCode & 剑指offer刷题】链表题8:35 复杂链表的复制(138. Copy List with Random Pointer)
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
138. Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
/*
问题:复制带随机指针的链表
方法:在原链表内部复制链表结点,由内部关系,复制随机指针连接关系,再进行拆分
*/
class
Solution
{
public
:
RandomListNode
*
copyRandomList
(
RandomListNode
*
head
)
{
//第一步:复制结点与next指针
RandomListNode
*
cur
=
head
;
while
(
cur
!=
nullptr
)
{
RandomListNode
*
node
=
new
RandomListNode
(
cur
->
label
);
//构造函数会将next和random指针赋值为null
node
->
next
=
cur
->
next
;
//新结点与旧结点连接
cur
->
next
=
node
;
//旧结点与新结点连接
cur
=
node
->
next
;
//下个旧结点
}
//第二步:复制random指针
cur
=
head
;
while
(
cur
!=
nullptr
)
{
if
(
cur
->
random
!=
nullptr
)
cur->next->random = cur->random->next;
//复制random指针 (cur->next为新结点)
cur
= cur->next->next; //下个旧结点
}
//第三步:拆分链表
cur
=
head
;
RandomListNode prehead
(
0
);
//创建整个链表的空头结点,方便处理
prehead.next = head;
RandomListNode
*
newcur
=
&
prehead
;
while
(
cur
!=
nullptr
)
{
cur->next = cur->next->next;
newcur
=
newcur
->
next
;
//更新指针
cur
=
cur
->
next
;
//cur走在newcur前面,方便判断
}
return
prehead
.
next
;
}
};