public RandomListNode CopyRandomList(RandomListNode head) { if (head == null) { return(head); } RandomListNode p = head; Dictionary <RandomListNode, RandomListNode> dct = new Dictionary <RandomListNode, RandomListNode>(); while (p != null) { dct.Add(p, new RandomListNode(p.label)); p = p.next; } p = head; while (p != null) { dct[p].next = p.next != null? dct[p.next]:null; dct[p].random = p.random != null ? dct[p.random] : null; p = p.next; } return(dct[head]); }
public RandomListNode CopyRandomList1(RandomListNode head) { if (head == null) { return(head); } RandomListNode p = head; while (p != null) { RandomListNode pnext = p.next; RandomListNode next = new RandomListNode(p.label); p.next = next; next.next = pnext; p = pnext; } p = head; while (p != null) { RandomListNode pnext = p.next; if (p.random != null) { pnext.random = p.random.next; } p = pnext.next; } RandomListNode newHead = head.next; p = head; while (p != null) { RandomListNode pnext = p.next; p.next = pnext.next; p = p.next; if (p != null) { pnext.next = p.next; } } return(newHead); }