複製帶隨機指標的連結串列(leetcode中級篇一百三十八題)
阿新 • • 發佈:2018-12-16
給定一個連結串列,每個節點包含一個額外增加的隨機指標,該指標可以指向連結串列中的任何節點或空節點。
ps:要求返回這個連結串列的深度拷貝
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* struct RandomListNode *next;
* struct RandomListNode *random;
* };
*/
typedef struct RandomListNode RLNode;
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
RLNode* cur = head;
while(cur)//複製連結串列
{
RLNode* next = cur -> next;
RLNode* copy = (RLNode*)malloc(sizeof(RLNode));
copy -> label = cur -> label;
cur -> next = copy;
copy -> next = next;
cur = next;
}
cur = head;
while(cur)//調整指標
{
RLNode* copy = cur -> next;
if(cur -> random)
{
copy -> random = cur -> random -> next;
}
else
{
copy -> random = NULL ;
}
cur = copy -> next;
}
RLNode* tail, *copyhead;
tail = copyhead = (RLNode*)malloc(sizeof(RLNode));
cur = head;
while(cur)//進行拆解
{
RLNode* copy = cur -> next;
RLNode* next = copy -> next;
tail -> next = copy;
tail = copy;
cur -> next = next;
cur = next;
}
RLNode* newnode = copyhead -> next;
free(copyhead);
return newnode;
}