• Copy List with Random Pointer leetcode


    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.

    Subscribe to see which companies asked this question

    1、在链表中依次插入新的结点
    2、构建新节点random指针:newNode->random = oldNode->random->next
    3、恢复原始链表以及构建新链表:例如old->next = old->next->next,  new->next = new->next->next
     
    RandomListNode *copyRandomList(RandomListNode *head) {
        if (head == nullptr)
            return nullptr;
        RandomListNode *iter = head;
        while (iter != nullptr)
        {
            RandomListNode *newNode = new RandomListNode(iter->label);
            newNode->next = iter->next;
            iter->next = newNode;
            iter = newNode->next;
        }
        iter = head;
        RandomListNode *iter1;
        while (iter != nullptr)
        {
            iter1 = iter->next;
            if(iter->random != nullptr)
                iter1->random = iter->random->next;
            iter = iter1->next;
        }
        RandomListNode *ret;
        ret = head->next;
        iter1 = ret;
        head->next = ret->next;
        iter = head->next;
        while (iter != nullptr)
        {
            iter1->next = iter->next;
            iter1 = iter1->next;
            iter->next = iter1->next;
            iter = iter->next;
        }
        return ret;
    }
  • 相关阅读:
    Bean生命周期
    Bean的作用域
    神经网络训练中,傻傻分不清Epoch、Batch Size和迭代
    jQuery中选择器有哪几种
    数据库的事务机制
    多线程面试题
    HTTP请求报文和HTTP响应报文
    linux tomcat单机部署多应用
    flexbox预习
    作业
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5134463.html
Copyright © 2020-2023  润新知