[leetcode] Copy List with Random Pointer

来源:互联网 发布:mac音量键在哪里设置 编辑:程序博客网 时间:2024/06/07 01:56

Copy List with Random Pointer

先在原来的链表上复制节点,然后拆分。

/** * 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 *cur=head;        while(cur!=nullptr){            RandomListNode *node=new RandomListNode(cur->label);//新建节点            node->next=cur->next;            cur->next=node;            cur=node->next;        }//N1M1N2M2...                cur=head;        while(cur!=nullptr){            if(cur->random!=NULL){                cur->next->random=cur->random->next;//拷贝random            }            cur=cur->next->next;        }                //分拆两个单链表        cur=head;        RandomListNode *new_Cur=new RandomListNode(0);        RandomListNode *new_List=new_Cur;        while(cur!=nullptr){            new_Cur->next=cur->next;            cur->next=cur->next->next;            cur=cur->next;            new_Cur=new_Cur->next;        }        return new_List->next;    }};


0 0
原创粉丝点击