复杂链表的复制(递归的两种实现方式)

题目描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),

返回结果为复制后复杂链表的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     {
15         if(pHead == null) return null;
16         RandomListNode head = new RandomListNode(pHead.label) ;//生成头节点
17         if(pHead.next != null){
18             head.next = new RandomListNode(pHead.next.label);    //生成头节点的next节点
19         }
20         if(pHead.random != null){
21             head.random = new RandomListNode(pHead.random.label);//生成头节点的random节点
22         }
23         copy(pHead,head);
24         return head;
25         
26     }
27     public void copy(RandomListNode node1,RandomListNode node2){
28         if(node1.next != null){
29             node2.next = new RandomListNode(node1.next.label);
30         }
31         if(node1.random != null){
32             node2.random = new RandomListNode(node1.random.label);
33         }
34         if(node1.next != null){
35             copy(node1.next, node2.next);        //递归循环
36         }                  
37     }
38 }

二、运用while实现递归

 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  
14     public RandomListNode Clone(RandomListNode pHead) {
15         if(pHead == null) { return null ; }
16  
17         RandomListNode head = new RandomListNode(pHead.label) ;
18         RandomListNode temp = head ;
19  
20         while(pHead.next != null) {
21             temp.next = new RandomListNode(pHead.next.label) ;
22             if(pHead.random != null) {
23                 temp.random = new RandomListNode(pHead.random.label) ;
24             }
25             pHead = pHead.next ;         //相当于递归,传入到下次计算的节点是本次计算的下一个节点
26             temp = temp.next ;
27         }
29         return head ;
30     }
32 }
原文地址:https://www.cnblogs.com/XuGuobao/p/7427169.html