zoukankan      html  css  js  c++  java
  • Leetcode#138 Copy List with Random Pointer

    原题地址

    非常巧妙的方法,不需要用map,只需要O(1)的额外存储空间,分为3步:

    1. 先复制链表,但是这个复制比较特殊,每个新复制的节点添加在原节点的后面,相当于"加塞"
    2. 根据原节点的 ramdon 指针构造新节点的 random 指针
    3. 恢复原链表结构,同时得到新复制链表

    时间复杂度:O(n)

    注意random有可能是NULL

    代码:

     1 RandomListNode *copyRandomList(RandomListNode *head) {
     2   RandomListNode *h = NULL;
     3 
     4   h = head;
     5   while (h) {
     6     RandomListNode *node = new RandomListNode(h->label);
     7     node->next = h->next;
     8     h->next = node;
     9     h = h->next->next;
    10   }
    11 
    12   h = head;
    13   while (h) {
    14     h->next->random = h->random? h->random->next : NULL;
    15     h = h->next->next;
    16   }
    17 
    18   h = head? head->next : NULL;
    19   while (head) {
    20     RandomListNode *tmp = head->next;
    21     head->next = head->next->next;
    22     tmp->next = head->next ? head->next->next : NULL;
    23     head = head->next;
    24   }
    25 
    26   return h;
    27 }
  • 相关阅读:
    sql执行顺序图
    solor5.4学习笔记
    linux 安装
    falsh,.swf文件修改z-index
    mysql 分区
    再次构架心得
    服务器,数据库连接注意mysql的user表
    数据库操作
    一知半见的load与get
    处理中文空格.replace((char)12288,' ')
  • 原文地址:https://www.cnblogs.com/boring09/p/4236001.html
Copyright © 2011-2022 走看看