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

    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

     1 /*
     2 public class RandomListNode {
     3     int label;
     4     RandomListNode next = null;
     5     RandomListNode random = null;
     6 
     7     RandomListNode(int label) {
     8         this.label = label;
     9     }
    10 }
    11 */
    12 public class Solution {
    13     public RandomListNode Clone(RandomListNode pHead){
    14         if(pHead==null)
    15             return null;
    16         RandomListNode pCur = pHead;
    17         //复制next 如原来是A->B->C 变成A->A'->B->B'->C->C'
    18         while(pCur!=null){
    19             RandomListNode node = new RandomListNode(pCur.label);
    20             node.next = pCur.next;
    21             pCur.next = node;
    22             pCur = node.next;
    23         }
    24         pCur = pHead;
    25         //复制random pCur是原来链表的结点 pCur.next是复制pCur的结点
    26         while(pCur!=null){
    27             if(pCur.random!=null)
    28                 pCur.next.random = pCur.random.next;
    29             pCur = pCur.next.next;
    30         }
    31         RandomListNode head = pHead.next;
    32         RandomListNode cur = head;
    33         pCur = pHead;
    34         //拆分链表
    35         while(pCur!=null){
    36             pCur.next = pCur.next.next;
    37             if(cur.next!=null)
    38                 cur.next = cur.next.next;
    39             cur = cur.next;
    40             pCur = pCur.next;
    41         }
    42         return head;        
    43     }
    44 }
  • 相关阅读:
    第七周学习进度
    环形数组求子数组最大和
    第六周学习进度
    团队
    子数组和最大值
    第五周学习进度
    第四周学习进度
    构建之法第一篇阅读笔记
    关于Sublime text 的PHP编译环境配置的问题
    PHP基础之 数组(二)
  • 原文地址:https://www.cnblogs.com/LoganChen/p/6473822.html
Copyright © 2011-2022 走看看