[leetcode] Copy List with Random Pointer

来源:互联网 发布:bit.edu.cn哪个是域名 编辑:程序博客网 时间:2024/05/03 20:30

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.

思路:先在原节点的后面复制前一个节点,这样的话原节点p->random就可以通过p->next->random=p->random->next进行复制,最后拆分节点就得到了复制的list

代码:

/** * 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) {        if(head==NULL) return NULL;        RandomListNode *res;        RandomListNode *temp=head,*temp2=head->next;        while(temp!=NULL){            temp->next=new RandomListNode(temp->label);            temp->next->next=temp2;            temp=temp2;            if(temp2!=NULL){                temp2=temp2->next;            }        }        temp=head; temp2=head->next;        while(temp!=NULL){            if(temp->random!=NULL){                if(temp->next!=NULL) temp2->random=temp->random->next;            }            if(temp->random==NULL){                temp2->random=NULL;            }            temp=temp->next->next;            if(temp2->next!=NULL){                temp2=temp2->next->next;            }        }        res=head->next;        temp=head; temp2=head->next;        while(temp2->next!=NULL){            temp->next=temp2->next;            temp=temp2;            if(temp2->next!=NULL){                temp2=temp2->next;            }        }        temp->next=NULL;        temp2->next=NULL;        return res;    }};


0 0
原创粉丝点击