# 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.

random 指针指向的是 原链表节点 random 指针指向的节点的后面的那个节点

Step 2: 将链表拆成两个 lists

C++实现代码：

#include<iostream>
#include<new>
using namespace std;

// 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:
{
return NULL;
while(p)
{
RandomListNode *q=new RandomListNode(p->label);
q->next=p->next;
p->next=q;
p=q->next;
}
while(p)
{
if(p->random)
p->next->random=p->random->next;
p=p->next->next;
}
RandomListNode *tRet = NULL;
while(p)
{
{
p->next = p->next->next;
p = p->next;
}
else
{
tRet->next = p->next;
p->next = p->next->next;
p = p->next;
tRet = tRet->next;
}
}
}
{
RandomListNode *p=NULL;
int i=0;
int arr[10]= {10,9,8,7,6,5,4,3,2,1};
for(i=0; i<10; i++)
{
{
return;
}
else
{
p=new RandomListNode(arr[i]);
}
}
}
};

int main()
{
Solution s;
RandomListNode *L=NULL;
s.createList(L);
RandomListNode *L2=s.copyRandomList(L);
RandomListNode *p=L2;
while(p)
{
cout<<p->label<<" ";
p=p->next;
}
}

|
10月前
|
C++
Leetcode Copy List with Random Pointer（面试题推荐）

40 0
LeetCode 382. Linked List Random Node

57 0
LeetCode 138：复制带随机指针的链表 Copy List with Random Pointer

834 0
|
DataX 程序员 算法

1031 0
|
Java
java中copy 一个list集合的方法
3014 0
[LeetCode] Copy List with Random Pointer
Well, since we need to make a deep copy of the list and nodes in the list have a random pointer that may point to any node in the list (or NULL), we n...
781 0