/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
typedef struct Node Node;
Node* copyRandomList(Node* head) {
if (head != NULL) {
// 1.在cur后面copy一份cur
for (Node* cur = head; cur != NULL; cur=cur->next->next) {
Node* newnode = (Node*)malloc(sizeof(Node));
newnode->val = cur->val;
newnode->next = cur->next;
cur->next = newnode;
}
// 2.将每个copy的节点的random指针补充完整
for (Node* cur = head; cur != NULL; cur=cur->next->next) {
Node* newnode = cur->next;
newnode->random = cur->random ? cur->random->next : NULL;
}
// 3.将copy的节点依次取下
Node* newhead = head->next;
for (Node* cur = head; cur != NULL; cur = cur->next) {
Node* newnode = cur->next;
cur->next = cur->next->next;
newnode->next = newnode->next ? newnode->next->next : NULL;
}
return newhead;
}
return NULL;
}
【leetcode】138. 随机链表的复制
最新推荐文章于 2025-04-20 00:50:25 发布