劍指Offer - 複雜連結串列的複製(Java語言實現)
阿新 • • 發佈:2018-12-04
題目描述
輸入一個複雜連結串列(每個節點中有節點值,以及兩個指標,一個指向下一個節點,另一個特殊指標指向任意一個節點),返回結果為複製後複雜連結串列的head。(注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空)
思路分析:
方法1,藉助HashMap。
遍歷連結串列,依次將節點作為鍵(KEY)存入Map集合中,新建一個RandomListNode物件並將當前key的數值傳入該物件中,並講該物件作為值(Value)存入。
再次遍歷連結串列,以該節點為key的值得next物件就是以當前節點的next物件為key的value物件。
同理,可以獲得複製連結串列的隨機指標物件。
程式碼如下:
public class Solution { public RandomListNode Clone(RandomListNode pHead) { HashMap<RandomListNode,RandomListNode> hm = new HashMap<>(); RandomListNode cur = pHead; while(cur != null){ hm.put(cur ,new RandomListNode(cur.label)); cur = cur.next; } cur = pHead; while(cur != null){ hm.get(cur).next = hm.get(cur.next); hm.get(cur).random = hm.get(cur.random); cur = cur.next; } return hm.get(pHead); } }
方法2
不需要藉助額外空間,遍歷原連結串列將連結串列的節點的下個節點全部改變成複製的節點,切該複製節點的下個節點指向原節點的下個節點,依次類推。如下圖所示,接著繼續重構新連結串列即可
程式碼實現如下:
public class Solution { public RandomListNode Clone(RandomListNode pHead) { if(pHead == null){ return null; } RandomListNode cur = pHead; RandomListNode next = null; //重構連結串列 while(cur != null){ next = cur.next; cur.next = new RandomListNode(cur.label); cur.next.next = next; cur = next; } cur = pHead; RandomListNode copyNode = null; //給新連結串列賦予random指標 while(cur != null){ next = cur.next.next; copyNode = cur.next; copyNode.random = cur.random != null ? cur.random.next : null; cur = next; } cur = pHead; RandomListNode res = pHead.next;; //給新連結串列賦予next指標,並將原始連結串列還原。 while(cur != null){ next = cur.next.next; copyNode = cur.next; cur.next = next; copyNode.next = next != null ? next.next : null; cur = next; } return res; } }