zoukankan      html  css  js  c++  java
  • 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;
        }

     

  • 相关阅读:
    4-11
    4-10
    4-9
    4-7
    4-8
    4-6
    4-4
    4-5
    4-3
    4-2
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4495880.html
Copyright © 2011-2022 走看看