您的位置:首页 > 运维架构

leetcode 之Copy List with Random Pointer(23)

2016-05-21 15:29 381 查看
RandomListNode *randomList(RandomListNode *head)
{
//复制每个结点,并将新结点放在旧结点之后
for (RandomListNode *cur = head; cur != nullptr;)
{
RandomListNode *node = new RandomListNode(cur->label);
node->next = cur->next;
cur->next = node;
cur = node->next;
}

//修改新结点的Random指针
for (RandomListNode *cur = head; cur != nullptr;)
{
if (cur->random != nullptr)cur->next->random = cur->random->next;

cur = cur->next->next;
}

//将新旧链表断开
RandomListNode dummy(-1);
for (RandomListNode *cur = head,*new_cur=&dummy; cur != nullptr;)
{
new_cur->next = cur->next;
new_cur = new_cur->next;

cur->next = cur->next->next;
cur = cur->next;

}

return dummy.next;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: