复杂链表的复制(递归的两种实现方式)
生活随笔
收集整理的這篇文章主要介紹了
复杂链表的复制(递归的两种实现方式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述:輸入一個復雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),
返回結果為復制后復雜鏈表的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
總結
以上是生活随笔為你收集整理的复杂链表的复制(递归的两种实现方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 板邓:【WordPress文件解读】wp
- 下一篇: 20170825 - Q - 集合框架