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.

解题思路:分三步走,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 || Copy List with Random Pointer


下一篇:springMvc配置xml使ResponseBody返回Json