zoukankan      html  css  js  c++  java
  • 26 复杂链表的复制

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

    C++:

     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         if (pHead == NULL)
    15             return NULL ;
    16         // 插入新节点
    17         RandomListNode* cur = pHead ;
    18         while(cur != NULL){
    19             RandomListNode* clone = new RandomListNode(cur->label) ;
    20             clone->next = cur->next ;
    21             clone->random = NULL ;
    22             
    23             cur->next = clone ;
    24             cur = clone->next ;
    25         }
    26         
    27         // 建立 random 链接
    28         cur = pHead ;
    29         while(cur != NULL){
    30             RandomListNode* clone = cur->next ;
    31             if (cur->random != NULL){
    32                 clone->random = cur->random->next ;
    33             }
    34             cur = clone->next ;
    35         }
    36         
    37         // 拆分
    38         cur = pHead ;
    39         RandomListNode* pCloneHead = pHead->next ;
    40         while(cur->next != NULL){
    41             RandomListNode* p = cur->next ;
    42             cur->next = p->next ;
    43             cur = p ;
    44         }
    45         return pCloneHead ;
    46     }
    47 };
  • 相关阅读:
    ZOJ3513_Human or Pig
    ZOJ2083_Win the Game
    ZOJ2725_Digital Deletions
    ZOJ2686_Cycle Gameu
    UVALive
    ZOJ2290_Game
    ZOJ3067_Nim
    P3159 [CQOI2012]交换棋子(费用流)
    P3153 [CQOI2009]跳舞(最大流多重匹配)
    P3121 [USACO15FEB]审查(黄金)Censoring (Gold)(ac自动机)
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8991103.html
Copyright © 2011-2022 走看看