• LeetCode【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.

    看上去比较复杂,实际上也比普通的链表题复杂。两个思路,一个用hash表,存储旧地址和新地址,然后对应一一copy;第二个思路,就和剑指offer里面提到的那样,在每个节点后创建一个副本,假设为copy,则在拷贝random指针时相对简单了。copy->random等于源节点的random指针的next节点。实现如下,已AC:

    RandomListNode *copyRandomList(RandomListNode *head) {
            if(!head)
                return head;
            // head is not NULL
            RandomListNode* h=head;
            //copy nodes and next pointers;
            while(h)
            {
                RandomListNode* copy = new RandomListNode(h->label);
                copy->next = h->next;
                h->next = copy;
                h=copy->next;
            }
            
            //copy random pointers
            h=head;
            while(h)
            {
                if(h->random)
                    h->next->random = h->random->next;
                h=h->next->next;
            }
            //split
            h=head;
            RandomListNode* newHead=head->next;
            while(h)
            {   
                RandomListNode* newH= h->next;
                h->next = newH->next;
                h=newH->next;
                if(h)
                    newH->next = h->next;
                else
                    newH->next = h;
            }
            return newHead;
        }

     

  • 相关阅读:
    如何开启无线网卡
    E-SATA接口
    sata express接口
    联想服务器驱动
    国家信息安全漏洞共享平台
    SQL SERVER 性能调优
    计算机网络知识库
    CCNP 视频
    ORACLE 培训 -相克军
    phxsql
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4495880.html
Copyright © 2020-2023  润新知