A linked list is given such that each node contains an additional
random pointer which could point to any node in the list or null.Return a deep copy of the list.node
建立一個HashMap, key爲原節點, value爲複製的節點. 而後遍歷一遍原鏈表, 把random指針負值給新的鏈表dom
時間O(n) 空間O(n)指針
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) { return head; } RandomListNode newHead = new RandomListNode(head.label); Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); map.put(head, newHead); RandomListNode node = head.next; RandomListNode pre = newHead; while (node != null) { RandomListNode tmp = new RandomListNode(node.label); map.put(node, tmp); pre.next = tmp; node = node.next; pre = pre.next; } node = head; pre = newHead; while (node != null) { pre.random = map.get(node.random); node = node.next; pre = pre.next; } return newHead; } }
深度拷貝一個鏈表code
第一步:複製鏈表並插入原鏈表原鏈表(1->2->3->4)新鏈表(1->1'->2->2'->3->3'->4->4')
第二步: 改變新鏈表的random指針
第三步:分離連個鏈表
注意這裏要斷定邊界條件get
時間O(n) 遍歷三遍鏈表 空間O(1)it
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) { return head; } RandomListNode node = head; while (node != null) { RandomListNode tmp = new RandomListNode(node.label); tmp.next = node.next; node.next = tmp; node = node.next.next; } node = head; while (node != null) { if (node.random != null) { node.next.random = node.random.next; } node = node.next.next; } RandomListNode newHead = head.next; node = head; while (node != null) { RandomListNode tmp = node.next; node.next = tmp.next; if (tmp.next != null) { tmp.next = tmp.next.next; } node = node.next; } return newHead; } }