输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:首先遍历一遍原链表,创建新链表(赋值label和next),用map关联对应结点;再遍历一遍,更新新链表的random指针。(注意map中应有NULL ----> NULL的映射)
import java.util.HashMap; import java.util.Map; /* public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } */ public class Solution { public RandomListNode Clone(RandomListNode pHead) { if (pHead == null) { return null; } RandomListNode pHead1 = pHead; RandomListNode pHead2 = new RandomListNode(pHead.label); RandomListNode newHead = pHead2; Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); map.put(pHead1, pHead2); while (pHead1 != null) { if (pHead1.next != null) { pHead2.next = new RandomListNode(pHead1.next.label); } else { pHead2.next = null; } pHead1 = pHead1.next; pHead2 = pHead2.next; map.put(pHead1, pHead2); } pHead1 = pHead; pHead2 = newHead; while (pHead1 != null) { pHead2.random = map.get(pHead1.random); pHead1 = pHead1.next; pHead2 = pHead2.next; } return newHead; } }