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

LeetCode 138. Copy List with Random Pointer

2016-03-23 20:26 281 查看
题目描述:

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.

解题思路:

我也不记得这道题在哪里看到过, 基本思路就是在原链表上复制每一个节点, 到原来节点的后面, 然后修复random pointers, 最后再将复制出来的节点, 从原链表中分离出来。



代码如下:

class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// 为每一个节点做一个备份, 插入原链表
RandomListNode *pcur = head;
while (pcur){
RandomListNode * newNode = new RandomListNode(pcur->label);
newNode->next = pcur->next;
pcur->next = newNode;
pcur = pcur->next->next;
}

// 复制random pointers
pcur = head;
while (pcur){
RandomListNode * pNext = pcur->next;
if (pcur->random)
pNext->random = pcur->random->next;
pcur = pcur->next->next;
}

// 分割链表
RandomListNode myhead(0);
RandomListNode * pre = &myhead;
pcur = head;
while (pcur){
RandomListNode * pNext = pcur->next;
pcur->next = pNext->next;
pcur = pcur->next;
pre->next = pNext;
pNext->next = nullptr;
pre = pre->next;
}

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