题目来源:. - 力扣(LeetCode)
题目描述:
测试用例:
大体意思就是复制一个一摸一样链表出来,看到这有些人就会想复制链表吗谁不会,但仔细看题可知,链表中还存储一个random,这样就使我们不知道如何操作了。大致介绍一下思路。
思路:
我们在原链表的基础上,在每个结点后边创建一个与前结点一模一样的结点,把他们插进原链表,然后根据原链表random指向的结点,让新创建节点的的randm指向原结点random的下一个结点的next:然后把新创建的结点在尾插下来就可以了
图示:
插入后:
步骤:1.首先创建新节点尾插到每个原节点的后边
//在链表基础上赋值链表
ListNode* cur=head;
while(cur){
ListNode* Newnode=(ListNode*)malloc(sizeof(ListNode));
Newnode->val=cur->val;
Newnode->next=cur->next;
cur->next=Newnode;
cur=Newnode->next;
}
步骤:2.随机数拷贝设置
//随机数设置
cur=head;
while(cur){
ListNode* copy=cur->next;
if(cur->random == NULL){
copy->random=cur->random;
}else{
copy->random=cur->random->next;
}
cur=copy->next;
}
步骤:3.把链表拷贝下来(尾插)
cur=head;
//哨兵位
ListNode* Newhead=(ListNode*)malloc(sizeof(ListNode));
ListNode* tail=Newhead;
while(cur){
ListNode* copy=cur->next;
ListNode* next=copy->next;
tail->next=copy;
tail=tail->next;
cur->next=next;
cur=next;
}
完整代码:
typedef struct Node ListNode;
struct Node* copyRandomList(struct Node* head) {
if(head==NULL){
return NULL;
}
//在链表基础上赋值链表
ListNode* cur=head;
while(cur){
ListNode* Newnode=(ListNode*)malloc(sizeof(ListNode));
Newnode->val=cur->val;
Newnode->next=cur->next;
cur->next=Newnode;
cur=Newnode->next;
}
//随机数设置
cur=head;
while(cur){
ListNode* copy=cur->next;
if(cur->random == NULL){
copy->random=cur->random;
}else{
copy->random=cur->random->next;
}
cur=copy->next;
}
//把新链表解下尾插
// cur=head;
// ListNode* pphead=NULL;
// ListNode* ptail=NULL;
// while(cur){
// ListNode* copy=cur->next;
// ListNode* next=copy->next;
// if(ptail==NULL){
// pphead=ptail=copy;
// }else{
// ptail->next=copy;
// ptail=ptail->next;
// }
// cur->next=next;
// cur=next;
// }
// return pphead;
cur=head;
//哨兵位
ListNode* Newhead=(ListNode*)malloc(sizeof(ListNode));
ListNode* tail=Newhead;
while(cur){
ListNode* copy=cur->next;
ListNode* next=copy->next;
tail->next=copy;
tail=tail->next;
cur->next=next;
cur=next;
}
return Newhead->next;
}
运行测试: