• leetcode 之Copy List with Random Pointer(23)


    深拷贝一个链表,不同的是这个链表有个额外的随机指针。参考:http://blog.csdn.net/ljiabin/article/details/39054999

    做法非常的巧妙,分成三步,一是新建结点,并放在旧结点之后;二是修改新结点的random指针;三是将新旧链表断开。

    RandomListNode *randomList(RandomListNode *head)
          {
              //复制每个结点,并将新结点放在旧结点之后
              for (RandomListNode *cur = head; cur != nullptr;)
              {
                  RandomListNode *node = new RandomListNode(cur->label);
                  node->next = cur->next;
                  cur->next = node;
                  cur = node->next;
              }
    
              //修改新结点的Random指针
              for (RandomListNode *cur = head; cur != nullptr;)
              {
                  if (cur->random != nullptr)cur->next->random = cur->random->next;
    
                  cur = cur->next->next;
              }
    
              //将新旧链表断开
              RandomListNode dummy(-1);
              for (RandomListNode *cur = head,*new_cur=&dummy; cur != nullptr;)
              {
                  new_cur->next = cur->next;
                  new_cur = new_cur->next;
    
                  cur->next = cur->next->next;
                  cur = cur->next;
    
              }
    
              return dummy.next;
          }
    View Code
  • 相关阅读:
    IGV解读
    box-cox解读
    linux命令eval的用法
    R中导入excel乱码的解决办法
    Django下实现HelloWorld
    python的list求和与求积
    win10下安装Django
    python下实现汉诺塔
    (stm32f103学习总结)—DS18B20
    (stm32f103学习总结)—GPIO结构
  • 原文地址:https://www.cnblogs.com/573177885qq/p/5514839.html
Copyright © 2020-2023  润新知