zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    hdu 3440 House Man
    hdu 2018 母牛的故事
    poj 1639 Picnic Planning 度限制mst
    uva 10870
    矩阵快速幂 模板与简单讲解
    1118sync_binlog innodb_flush_log_at_trx_commit 浅析
    1117Mysql prepare预处理语句
    1116Xlinux初学习之正则表达式和通配符
    1111分析存储引擎
    1111MySQL配置参数详解
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10802932.html
Copyright © 2011-2022 走看看