复制带随机指针的链表 描述 笔记 数据 评测 给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。 返回一个深拷贝的链表。 样例 挑战 可否使用O(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: /** * @param head: The head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */ RandomListNode *copyRandomList(RandomListNode *head) { // write your code here if(head == NULL) return NULL; //复制的结点插入到原来的结点之后 RandomListNode *node = head; while(node!=NULL) { RandomListNode *clone = new RandomListNode(node->label); clone->next = node->next; node->next = clone; node=clone->next; } //设置random指针,O(N)复杂度 node = head; while(node!=NULL) { RandomListNode *clone = node->next; if(NULL != node->random) clone->random = node->random->next; node = clone->next; } //将偶数位的结点提取出来 node = head; RandomListNode *clonelist = node->next; node = clonelist->next; while(node!=NULL) { clonelist->next = node->next; node = node->next->next; clonelist = clonelist->next; } return head->next; } };