题目链接:https://leetcode.com/problems/copy-list-with-random-pointer/
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.
思路:这题是要做一个深copy,可以先建立好链表,然后再连random的指针。因为random的指针是随机的,所以在找新的每一个结点的random指针指向的结点的时候可以让新的链表和原来的链表每次从头同步走,直到碰到原来链表random指针指向的结点停止,然后将新链表的一个结点random指针指向走到的地方。时间复杂为O(n*n)。
代码如下:
/**
* 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:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head) return head;
RandomListNode *pHead = new RandomListNode(head->label);
RandomListNode *p=head->next, *q=pHead;
while(p)
{
RandomListNode *node = new RandomListNode(p->label);
q->next = node, p = p->next, q = q->next;
}
p = head, q = pHead;
while(p)
{
RandomListNode *tem1 = head, *tem2 = pHead;
while(p->random && tem1!=p->random) tem1=tem1->next, tem2=tem2->next;
if(p->random) q->random = tem2;
p = p->next, q = q->next;
}
return pHead;
}
};
还有一种就是对原链表和新链表做一个hash,可以在O(n)时间和空间完成
代码如下:
/**
* 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:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head) return head;
RandomListNode *pHead=new RandomListNode(head->label), *q=pHead, *p=head;
unordered_map<RandomListNode*, RandomListNode*> hash;
hash[head] = pHead;
while(p->next)
{
RandomListNode *node = new RandomListNode(p->next->label);
hash[p->next] = node;
q->next = node, q = q->next, p = p->next;
}
p = head;
while(p)
{
hash[p]->random = hash[p->random];
p = p->next;
}
return pHead;
}
};
还有一种可以在O(n)时间O(1)空间完成的方法.就是对原链表的每一个结点新建一个结点直接插入其后面,然后再链接新结点的random pointer, 再拆开这些新结点.