题目描述:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
/**
* 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) {}
* };
*/
// 用哈希表保存原链表和新链表中每个节点的对应关系,那么q->random = hash[p->random]
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return NULL;
RandomListNode *res = new RandomListNode(head->label);
RandomListNode *p = head->next;
RandomListNode *q = res;
unordered_map<RandomListNode*, RandomListNode*> hash;
hash[head] = res;
while (p) {//这个循环中p比q早一步,方便复制一个和p一样的节点,让q指向它
RandomListNode *tmp = new RandomListNode(p->label);
q->next = tmp;
hash[p] = tmp;
q = q->next;
p = p->next;
}
//这个循环中p和q同步
p = head;
q = res;
while (q) {
q->random = hash[p->random];
q = q->next;
p = p->next;
}
return res;
}
};
// 将新链表穿插在原链表中,空间复杂度为O(1)
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head)
{
if (!head) return NULL;
RandomListNode *p = head;
while (p)
{
RandomListNode *new_node = new RandomListNode(p->label);
new_node->next = p->next;
p->next = new_node;
p = new_node->next;
}
p = head;
while (p)
{
if (p->random) p->next->random = p->random->next; //复制random指针
p = p->next->next; //一次跳两步
}
p = head;
RandomListNode *res = head->next;
while (p)
{
RandomListNode * q = p->next;
if(p->next) p->next = p->next->next;
if(q->next) q->next = q->next->next;
p = p->next;
}
return res;
}
};