思路
- 将新结点放在老结点的后面
- 复制random
- 将链表拆开
/*
// Definition for a Node.
class Node {
public:int val;Node* next;Node* random;Node() {}Node(int _val, Node* _next, Node* _random) {val = _val;next = _next;random = _random;}
};
*/
class Solution {
public:Node* copyRandomList(Node* head) {if (head == NULL){return NULL;}Node *cur = head;while (cur != NULL){//新结点跟在老结点后面Node *node = (Node *)malloc(sizeof(Node));node->val = cur->val;node->random = NULL;Node *next = cur->next;cur->next = node;node->next = next; //原来cur->nextcur = next;}//复制randomcur = head;while (cur != NULL){Node *node = cur->next;if (cur->random != NULL){node->random = cur->random->next;}cur = node->next;}//拆开cur = head;Node *ret = head->next;while (cur != NULL){Node *node = cur->next;cur->next = node->next;if (node->next != NULL){node->next = cur->next->next;}cur = cur->next;}return ret;}
};