标签:之间 and 注意 https 遍历 一个 等于 href node
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
映射表
class Solution {
public:
Node* copyRandomList(Node* head) {
//建立新旧节点之间的映射表:old->new
map<Node*, Node*> table;
//第一次遍历:构造新链表,此时不对random指针进行赋值
Node dummy(-1);
Node *cur = head;
Node *new_cur = &dummy;
for(; cur != NULL; cur = cur->next, new_cur = new_cur->next){
int v = cur->val;
Node *new_node = new Node(v);
table[cur] = new_node; //关键点:建立旧节点指针到新节点指针的映射
new_cur->next = new_node;
}
//第二次遍历:对新链表的random指针进行赋值
cur = head;
new_cur = dummy.next;
for(; cur != NULL; cur = cur->next, new_cur = new_cur->next){
Node *r = cur->random;
Node *new_r = table[r];
new_cur->random = new_r;
}
return dummy.next;
}
};
克隆链表
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return head;
//copy new node and changing new node next pointer to old node next pointer and old node next pointer to new node
Node *newHead = NULL, *l1, *l2;
for(l1 = head; l1 != NULL; l1 = l1->next->next){
l2 = new Node(l1->val, l1->next, NULL);
l1->next = l2;
}
newHead = head->next;
//fixing the random pointer of the cloned list
for(l1= head; l1 != NULL; l1 = l1->next->next){
if(l1->random) l1->next->random = l1->random->next;
}
//changing the next node of both old and new list
for(l1 = head; l1 != NULL; l1 = l1->next){
l2 = l1->next;
l1->next = l2->next;
if(l2->next)l2->next = l2->next->next;
}
return newHead;
}
};
[LeetCode] 138. Copy List with Random Pointer
标签:之间 and 注意 https 遍历 一个 等于 href node
原文地址:https://www.cnblogs.com/wengle520/p/12330664.html