劍指offer——將複雜問題分解使其簡單化

題目描述

輸入一個複雜鏈表(每一個節點中有節點值,以及兩個指針,一個指向下一個節點,另外一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,不然判題程序會直接返回空)
思路1.
  •         直接先複製主鏈
  •         以後再重複遍歷,依次添加主鏈的隨機結點,時間複雜度爲O(n*n)
思路2.空間換取時間,
  •         首先複製主鏈,以後將主鏈與複製鏈之間採用哈希表進行兩條鏈間對應結點的配對信息;
  •         以後根據哈希表直接找到複製鏈中每一個結點的隨機結點,時間複雜度爲O(1)
思路3.不用輔助空間,實現O(n)時間效率
  •         首先複製原始鏈表中每一個結點N,並建立複製結點N‘,再將複製結點N’連接到結點N以後
  •         複製隨機結點,即若是N結點的隨機結點爲S,則N'的隨機結點爲S的後序結點S'
  •         按照位置提取奇偶位置結點組成新鏈。
源代碼以下所示(加入了是否爲空操做的判斷,不然會輸出警告)
 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 /*
13 1.在舊鏈表中建立新的鏈表,此時不處理新鏈表的兄弟鏈表
14 2.根據舊鏈表的兄弟結點,初始化新鏈表中的兄弟結點
15 3.從舊鏈表中拆分獲得新鏈表
16 */
17 public class Solution {
18     public RandomListNode Clone(RandomListNode pHead)
19     {
20         if (pHead==null)
21             return null;
22         RandomListNode currentNode = pHead;
23         //複製每一個結點,並將複製後的結點插入結點以後
24         while(currentNode != null){
25             RandomListNode cloneNode = new RandomListNode(currentNode.label);
26             RandomListNode nextNode = currentNode.next;
27             currentNode.next = cloneNode;
28             cloneNode.next = nextNode;
29             currentNode = nextNode;            
30         }
31         currentNode = pHead;
32         //從新遍歷鏈表,複製老結點的隨機指針給新結點
33         while(currentNode != null){
34             currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
35             currentNode = currentNode.next.next;
36         }
37         //拆分鏈表,將鏈表拆分爲原鏈表和複製後的鏈表
38         currentNode = pHead;
39         RandomListNode pCloneHead = pHead.next;
40         while(currentNode!=null){
41             RandomListNode cloneNode = currentNode.next;
42             currentNode.next = cloneNode.next;
43             cloneNode.next = cloneNode.next == null?null:cloneNode.next.next;
44             currentNode = currentNode.next;
45         }
46         return pCloneHead;
47     }
48 }
相關文章
相關標籤/搜索