題目描述
輸入一個複雜連結清單(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),傳回結果為複制後複雜連結清單的head。(注意,輸出結果中請不要傳回參數中的節點引用,否則判題程式會直接傳回空)
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead == NULL) return NULL;
RandomListNode* tail;
RandomListNode* head = (RandomListNode*)malloc(sizeof(RandomListNode));
tail = head;
head->label = pHead->label;
head->next = head->random = NULL;
RandomListNode* temp = pHead->next;
for(; temp != NULL; temp=temp->next)
{
RandomListNode* node;
node = (RandomListNode*)malloc(sizeof(RandomListNode));
node->label = temp->label;
tail->next = node;
tail = node;
node->next = node->random = NULL;
}
temp = pHead;
RandomListNode* node = head;
for(; temp != NULL; temp=temp->next)
{
if(temp->random != NULL)
{
RandomListNode *flag1,*flag2;
flag1 = pHead, flag2 = head;
while(flag1 != temp->random)
{
flag1 = flag1->next;
flag2 = flag2->next;
}
node->random = flag2;
}
node = node->next;
}
return head;
}