题目
**注意:**题目是真的绕!!!当然了也是自己不够熟练指针的题目!!!
继续加油骚年!!!
代码
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
// 不知道如何复制随机指针??
// head->random不能直接赋值吗????????
class Solution {
public:
Node* copyRandomList(Node* head) {
// 不能这样写,这样写相当于直接写return head!!!
// Node* dummpy_head = new Node(-1);
// Node* dummpy_tail = dummpy_head;
// while(head) {
// dummpy_tail->next = head;
// dummpy_tail = dummpy_tail->next;
// head = head->next;
// }
// return dummpy_head->next;
// 思路1:哈希表
// 思路2:copy指针
Node* dummpy_head = head;
// 1 -> 2 -> 3 变成 1 -> 1` -> 2 -> 2` -> 3 -> 3`
while(dummpy_head) {
Node* curr_copy = new Node(dummpy_head->val);
Node* next = dummpy_head->next;
dummpy_head->next = curr_copy;
curr_copy->next = next;
dummpy_head = dummpy_head->next->next;;
}
// 设定 random指针
dummpy_head = head;
while(dummpy_head) {
Node* curr_random = dummpy_head->random;
// 注意:此时curr_random可能为空
// 需要进行判断,判断是否为空
dummpy_head->next->random = curr_random ? curr_random->next : nullptr;
dummpy_head = dummpy_head->next->next;
}
// 分离出copy节点 与 原始节点
dummpy_head = head;
Node* new_head = new Node(-1);
Node* new_tail = new_head;
while(dummpy_head) {
// 分离出来的新copy的指针
new_tail->next = dummpy_head->next;
new_tail = new_tail->next;
// 原先的指针
dummpy_head->next = dummpy_head->next->next;
dummpy_head = dummpy_head->next;
}
return new_head->next;
}
};