leetcode 138. Copy List with Random Pointer

138. Copy List with Random Pointer

分三步:1.在原有list每个节点的后面增加与原节点值相同的节点

    2.在这些新生成的节点中增加随机节点

    3.将原有的节点和新生成的节点进行分离

注意:

if(cur->random)
randNode = cur->random->next;
else
randNode = NULL;

 

if(res->next)
res->next = res->next->next;
else
res->next = NULL;

这两个地方都要判断null的情况。还有这个代码不适合head == NULL的情况,所以一开始也要写为空的返回情况。

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head == NULL)
            return NULL;
        Node* cur = head;
        while(cur){
            Node* tmp = cur->next;
            Node* newNode = new Node(cur->val);
            cur->next = newNode;
            newNode->next = tmp;
            cur = tmp;
        }
        cur = head;
        while(cur){
            Node* tmp = cur->next;
            Node* randNode;
            if(cur->random)
                randNode = cur->random->next;
            else
                randNode = NULL;
            tmp->random = randNode;
            cur = cur->next->next;
        }
        cur = head;
        Node* res = head->next;
        Node* result = head->next;
        while(cur){
            cur->next = cur->next->next;
            if(res->next)
                res->next = res->next->next;
            else
                res->next = NULL;
            cur = cur->next;
            res = res->next;
        }
        return result;
    }
};

 

posted @ 2019-05-02 18:08  有梦就要去实现他  阅读(166)  评论(0编辑  收藏  举报