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

138. Copy List with Random Pointer

时间:2017-12-25 23:24:20      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:nal   for   ret   link   down   res   osd   插入   label   

欢迎fork and star:Nowcoder-Repository-github

138. Copy List with Random Pointer

题目

 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. 断开链表可得到深度拷贝后的新链表

技术分享图片


/**
 * 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)
            return NULL;
        //if (!head->next) //bug: 这句话bug,不加才行!!!
        //{
        //  RandomListNode* copy = new RandomListNode(head->label);
        //  return copy;
        //}

        RandomListNode* cur = head;

        RandomListNode* temp = NULL;
        while (cur) //在每个节点后面copy节点
        {
            RandomListNode* newNode = new RandomListNode(cur->label); //bug 在之后插入

            temp = cur->next;
            cur->next = newNode;
            newNode->next = temp;
            
            cur = cur->next->next;
        }

        //每个节点copy random指针

        cur = head;
        while (cur) //bug 指针越界
        {
            if (cur->random)
            {
                cur->next->random = cur->random->next; //??->next
            }
            cur=cur->next->next;
        }

        // 将original list和copy list分开

        cur = head;
        RandomListNode* copyHead = new RandomListNode(0);
        RandomListNode* copy_cur = copyHead;

        RandomListNode* next = NULL;
        while (cur)
        {
            next = cur->next->next;

            copy_cur->next = cur->next;
            copy_cur = cur->next;

            cur->next = next;
            cur = next;

        }

        return copyHead->next;

        /*RandomListNode*p = NULL;
        p = head;
        RandomListNode* res = head->next;
        while (p->next != NULL)
        {
            RandomListNode* tmp = p->next;
            p->next = p->next->next;
            p = tmp;
        }
        return res; */
    }
};

题目来源

138. Copy List with Random Pointer

标签:nal   for   ret   link   down   res   osd   插入   label   

原文地址:https://www.cnblogs.com/ranjiewen/p/8111384.html

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