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.
解法1:
/**
* 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) {
if (head == nullptr) return head;
RandomListNode *p = head;
while (p != nullptr) {
RandomListNode *pCloned = new RandomListNode(p->label);
pCloned->next = p->next;
p->next = pCloned;
p = pCloned->next;
}
p = head;
while (p != nullptr) {
if (p->random != nullptr)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
RandomListNode *pCloneHead = head->next, *pCloned = head->next;
while (p != nullptr) {
p->next = p->next->next;
if (pCloned->next != nullptr)
pCloned->next = pCloned->next->next;
p = p->next;
pCloned = pCloned->next;
}
return pCloneHead;
}
};解法2:
/**
* 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) {
RandomListNode *p = nullptr, *pCloned = nullptr, *pClonedHead = nullptr;
map<RandomListNode*, int> mp;
int pos = 0;
for (p = head; p != nullptr; p = p->next) {
mp[p] = pos++;
}
vector<RandomListNode*> vec;
for (p = head; p != nullptr; p = p->next) {
RandomListNode *node = new RandomListNode(p->label);
vec.push_back(node);
if (pClonedHead == nullptr) {
pClonedHead = node;
pCloned = node;
}
else {
pCloned->next = node;
pCloned = node;
}
}
for (pCloned = pClonedHead, p = head; pCloned != nullptr && p != nullptr; p = p->next, pCloned = pCloned->next) {
if (p->random != nullptr) {
pos = mp[p->random];
pCloned->random = vec[pos];
}
}
return pClonedHead;
}
};
本文介绍两种深拷贝含随机指针的单链表方法。方法一通过在原节点间插入克隆节点并调整指针完成;方法二使用哈希映射记录节点位置,创建新链表并根据映射设置随机指针。
943

被折叠的 条评论
为什么被折叠?



