码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-138-Copy List with Random Pointer

时间:2019-02-06 14:30:29      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:null   链表   pre   addition   node   could   tno   nal   tco   

算法描述:

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.

解题思路:分三步走,1 在每个节点后面复制该节点;2 复制随机指针 cur->next->random = cur->random->next; 3将两个链表分离。

    RandomListNode *copyRandomList(RandomListNode *head) {
        if(head == nullptr) return head;
        RandomListNode* cur = head;
        while(cur!=nullptr){
            RandomListNode* temp = new RandomListNode(cur->label);
            temp->next = cur->next;
            cur->next = temp;
            cur = cur->next->next;
        }
        RandomListNode* newHead = head->next;
        cur = head;
        while(cur!=nullptr){
            if(cur->random!=nullptr)
                cur->next->random = cur->random->next;
            cur = cur->next->next;
        }
        cur = head;
        RandomListNode* ncur = newHead;
        while(cur!=nullptr){
            cur->next = ncur->next;
            cur = cur->next;
            if(cur!=nullptr){
                ncur->next = cur->next;
                ncur= ncur->next;
            }
        }
        return newHead;
    }

 

LeetCode-138-Copy List with Random Pointer

标签:null   链表   pre   addition   node   could   tno   nal   tco   

原文地址:https://www.cnblogs.com/nobodywang/p/10353641.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!