• leetcode 13:copy-list-with-random-pointer


    题目描述

    现在有一个这样的链表:链表的每一个节点都附加了一个随机指针,随机指针可能指向链表中的任意一个节点或者指向空。
    请对这个链表进行深拷贝。
    题目分析:
    如果要做到深拷贝,分一下三个步骤:1.分别创建新链表的节点,插入到旧表中 2.根据旧表中的节点复制随机指针 3.剥离旧表和新表,返回新表的头结点。注意指针间的处理即可,属于常规题
    代码如下:
     1 RandomListNode *copyRandomList(RandomListNode *head) {
     2         RandomListNode* copy;
     3         RandomListNode* cur;
     4         if(!head)
     5             return NULL;
     6         cur = head;
     7         //插入旧表中
     8         while(cur)
     9         {
    10             copy = new RandomListNode(cur->label);
    11             copy->next = cur->next;
    12             cur->next = copy;
    13             cur = cur->next->next;
    14         }
    15         //复制随机指针
    16         cur = head;
    17         while(cur)
    18         {
    19             copy = cur->next;
    20             copy->random = (cur->random?cur->random->next:NULL);
    21             cur = copy->next;
    22         }
    23         //复制的链表从旧表中剥离
    24         cur = head;
    25         copy = cur->next;
    26         head = copy;
    27         while(cur)
    28         {
    29             cur->next = copy->next;
    30             cur = cur->next;
    31             copy->next = (cur?cur->next:NULL);
    32             copy = copy->next;
    33         }
    34         return head;
    35     }
  • 相关阅读:
    MapReduce编程:数字排序
    MapReduce编程:平均成绩
    线性回归(linear regression)
    pip安装第三方库镜像源选择
    malloc/free 和 new/delete
    strcpy函数解析
    牛客-数据库SQL实战
    Numpy学习
    花式饺子
    MapReduce编程:单词去重
  • 原文地址:https://www.cnblogs.com/qingjiaowoxiaoxioashou/p/13496364.html
Copyright © 2020-2023  润新知