zoukankan      html  css  js  c++  java
  • 【剑指offer】复杂链表的复制

    题目链接:复杂链表的复制

     

    题意:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。

     

    题解:啊这个题我没看懂其实。我看了剑指的题解。大概就是要分三步

    1、复制指针的label和next。将复制的节点跟在原节点后面。然后创造新的链表。

    2、设置复制出来的新链表的random。

    3、分离新旧链表。

     

    代码:

     1 /*
     2 struct RandomListNode {
     3     int label;
     4     struct RandomListNode *next, *random;
     5     RandomListNode(int x) :
     6             label(x), next(NULL), random(NULL) {
     7     }
     8 };
     9 */
    10 class Solution {
    11 public:
    12     RandomListNode* Clone(RandomListNode* pHead)
    13     {
    14         RandomListNode* cur = pHead;
    15         RandomListNode* list = NULL;
    16         RandomListNode* tail = NULL;
    17         if(cur == NULL) return NULL;
    18         //复制原来的节点
    19         while(cur){
    20             RandomListNode* node = new RandomListNode(cur->label);
    21             RandomListNode* next = cur->next;
    22             
    23             cur->next = node;
    24             node->next = next;
    25             
    26             cur = node->next;
    27         }
    28         //random
    29         cur = pHead;
    30         while(cur){
    31             if(cur->random){
    32                 RandomListNode* next = cur->next;
    33                 next->random = cur->random->next;
    34             }
    35             else    cur->next->random = NULL;
    36             cur = cur->next->next;
    37         }
    38         
    39         list = tail = pHead->next;
    40         pHead->next = list->next;
    41         cur = pHead->next;
    42         while(cur){
    43             RandomListNode* copy = cur->next;
    44             cur->next = copy->next;
    45             
    46             tail->next = copy;
    47             tail = copy;
    48             
    49             cur = cur->next;
    50         }
    51         return list;
    52     }
    53 };
  • 相关阅读:
    1061. 判断题(15)
    1031. 查验身份证(15)
    1006. 换个格式输出整数 (15)
    1046. 划拳(15)
    1001. 害死人不偿命的(3n+1)猜想 (15)
    1021. 个位数统计 (15)
    1054. 求平均值 (20)
    写出这个数 (20)
    设计模式之中介者模式
    kill命令
  • 原文地址:https://www.cnblogs.com/Asumi/p/12404957.html
Copyright © 2011-2022 走看看