题目描述:
实现思路:
代码实现:
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* Buy_Capacity(int x)//每次插入(头插尾插)都要创建新节点,可以将此过程封装
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
if (newnode == NULL)//创建新节点失败
{
perror("malloc fail!");
return 0;
}
newnode->val = x;
newnode->next = newnode->random = NULL;
return newnode;
}
struct Node* copyRandomList(struct Node* head) {
//在每个节点后面拷贝插入一个新节点
struct Node*cur=head;
while(cur)
{
struct Node* newnode=Buy_Capacity(cur->val);
struct Node* next=cur->next;
cur->next=newnode;
newnode->next=next;
cur=cur->next->next;
}
//再建立新创建的节点之间random的关系
cur=head;
while(cur)
{
if(cur->random==NULL)
{
cur->next->random=NULL;
}
else
{
cur->next->random=cur->random->next;
}
cur=cur->next->next;
}
//最后断开原节点和新节点,并返回新节点的头
cur=head;
struct Node*newhead=NULL,*tail=NULL;//要记得初始化,否则会造成非法访问的问题
while(cur)
{
struct Node* list=cur->next->next;
if(newhead==NULL)
{
newhead=tail=cur->next;
cur->next=list;
}
else
{
tail->next=cur->next;
cur->next=list;
tail=tail->next;
}
cur=cur->next;
}
return newhead;
}