leetcode_c++:哈希: Copy List with Random Pointer(138)


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.


算法

O(N)
/*
* 程序用来复制一个复杂链表
* 复杂链表表示:存在2个指针,一个指针之后下一个节点,另外一个随机指针指向随机节点
* 分成3步:
* 1. 复制节点,如A-B-C 变成 A-A’-B-B’-C-C’
* 2. 依次遍历节点A,B,C,将这些节点的随机指针与A’B’C’一致
* 3. 分离A-B-C和A’B’C’,A’B’C’便是需要求得链表
* */


/**
 * 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) {
        RandomListNode *tHead = head;
        RandomListNode *next = NULL;
        while(tHead)
        {
            next = tHead->next;
            RandomListNode *node = new RandomListNode(tHead->label);
            node->next = tHead->next;
            //node->random = tHead->random;
            tHead->next = node;
            tHead= next;
        }
        tHead = head;
        while(tHead)
        {
            if(tHead->random) tHead->next->random = tHead->random->next;
            tHead = tHead->next->next;
        }
        RandomListNode *retHead = NULL;
        RandomListNode *tRet = NULL;

        tHead = head;
        RandomListNode *next2 = NULL;
        while(tHead)
        {
            if(retHead == NULL)
            {  
                next2 = tHead->next->next;
                retHead = tHead->next;
                tRet = retHead;
                tHead->next = next2;
                tHead = next2;
            }
            else
            {
                next2 = tHead->next->next;
                tRet->next = tHead->next;
                tHead->next = next2;
                tHead = next2;
                tRet = tRet->next;
            }

        }
        return retHead;
    }
};

你可能感兴趣的:(leetcode(c++))