Copy List with Random Pointer

来源:互联网 发布:ps美工字体打包下载 编辑:程序博客网 时间:2024/06/08 13:22

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

<span style="font-size:18px;">/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { *     int label; *     RandomListNode *next, *random; *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */class Solution {public:    RandomListNode *copyRandomList(RandomListNode *head) {        RandomListNode *copyhead,*copy_ptr,*tmp,*p=head;        if(!head)            return NULL;        while(p)//第一步往列表每一个元素后面插入一个元素,该元素的值与前一个相同        {            copy_ptr=new RandomListNode(p->label);            copy_ptr->next=p->next;            p->next=copy_ptr;            if(copy_ptr->next)                p=copy_ptr->next;            else                break;        }        p=head;        copy_ptr=head->next;        while(p)//第二步把random指针正确置位        {            if(p->random==NULL)                copy_ptr->random=NULL;            else                copy_ptr->random=p->random->next;            if(p->next)                p=p->next->next;            if(copy_ptr->next)                copy_ptr=copy_ptr->next->next;        }        copyhead=head->next;        copy_ptr=head->next;        p=head;    while(copy_ptr->next)//拆分两个链表    {                p->next=copy_ptr->next;        p=copy_ptr;        if(copy_ptr->next!=NULL)             copy_ptr=copy_ptr->next;      }    p->next=NULL;    return copyhead;    }};</span>


0 0
原创粉丝点击