給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。
要求返回這個鏈表的深度拷貝。
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* struct RandomListNode *next;
* struct RandomListNode *random;
* };
*/
typedef struct RandomListNode RLNote;
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
//第一步,先複製鏈表中的所有結點
RLNote *cur = head;
RLNote *next;
while(cur)
{
next = cur->next;
RLNote *copy =(RLNote *)malloc(sizeof(RLNote));
copy->label = cur->label;
cur->next = copy;
copy->next = next;
cur = next;
}
//第二步,將random連接起來
cur = head;
while(cur)
{
RLNote* copy = cur->next;
if(cur->random)
copy->random = cur->random->next;
else
copy->random = NULL;
cur = copy->next;
}
//第三步,將copy提取出來
RLNote* copyhead,* tail ;
copyhead = tail = (RLNote*)malloc(sizeof(RLNote));
cur = head;
while(cur)
{
RLNote* copy = cur->next;
RLNote* next = copy->next;
tail -> next = copy;
tail = copy;
//鏈接原鏈表的所有next
cur -> next = next;
//循環下一個時將cur指向next
cur = next;
}
RLNote* newnode = copyhead->next;
free(copyhead);
return newnode;
}