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;
        }
    };
  • 相关阅读:
    三数之和(排序+双指针)
    数值的整数次方(类快速幂)
    Z字形变换
    相交链表
    牛妹的蛋糕
    安置路灯
    迷路的牛牛
    Office 2003的卸载 与 Office 2013 的安装
    解决“飞鸽传书”无法显示局域网用户的方法
    bcd(Binary-Coded Decimal‎缩写)
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10802932.html
Copyright © 2011-2022 走看看