复杂链表的复制

题目描述

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

题目解析

这个题目主要的难点在于随机指向的这个节点如何去复制到另一个链表中去,那么,这里如果单纯的采用直接赋值拷贝的方式肯定是不可取的,因为这个方式的话需要遍历整个链表确定每个元素指向了第几个元素然后再次扫描并进行修改指向,这当然肯定不是最好的解决办法。

解题思路

既然要复制,那么平行的将每个元素复制一份作为一个拷贝,作为其原来元素的next插入到原来的链表中去,这样的话就形成了,A->A`->B->B`的链表,那么,在复制的过程中我们可以同时拷贝A的random来记录其random指向,注意random可以在后面做向后移动一个元素的方式进行获取。

所以这个题分两个步骤,

1.复制所有元素并将其添加为原来元素的next节点,同时复制random指向。

2.删除链表中原来的节点,将新的节点取出来,并且,链表中的random和next全部向后面平移一位。

代码实现

[java]  view plain  copy
  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.     {  
  15.         if(pHead == null) {  
  16.             return null;  
  17.         }  
  18.           
  19.         RandomListNode node = pHead;  
  20.         while(node != null) {  
  21.               
  22.             RandomListNode nodeCopy = new RandomListNode(node.label);  
  23.             nodeCopy.next = node.next;  
  24.             nodeCopy.random = node.random;  
  25.             node.next = nodeCopy;  
  26.               
  27.             node = node.next.next;  
  28.         }  
  29.           
  30.         node = pHead;  
  31.         int count = 0;  
  32.         RandomListNode head = null;  
  33.         RandomListNode temp = null;  
  34.           
  35.         while(node != null) {  
  36.               
  37.             if(count % 2 == 1) {  
  38.                   
  39.                 if(count == 1) {  
  40.                     head = node;  
  41.                 }  
  42.                 if(node.random != null) {  
  43.                     node.random = node.random.next;  
  44.                 }  
  45.                 temp = node.next;  
  46.                 if(node.next != null) {  
  47.                     node.next = node.next.next;  
  48.                       
  49.                 }  
  50.                 node = temp;   
  51.                   
  52.             } else {  
  53.                 node = node.next;  
  54.             }  
  55.               
  56.             count ++;  
  57.               
  58.         }  
  59.         pHead.next = null;  
  60.               
  61.         return head;  
  62.     }  
  63. }  


转载地址:https://blog.csdn.net/wangyang1354/article/details/73496752


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值