复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
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 public class Solution { 13 public RandomListNode Clone(RandomListNode pHead) 14 { 15 if (pHead == null) return null; 16 17 RandomListNode p, p1 = pHead; 18 19 RandomListNode nextNode; 20 while (p1 != null) { 21 nextNode = p1.next; 22 p1.next = new RandomListNode(p1.label); 23 p1.next.next = nextNode; 24 p1 = nextNode; 25 } 26 27 28 p1 = pHead; 29 while (p1 != null) { 30 if (p1.random != null) 31 p1.next.random = p1.random.next; 32 p1 = p1.next; 33 p1 = p1.next; 34 } 35 36 RandomListNode head = pHead.next; 37 p = pHead.next; 38 p1 = pHead; 39 while (p.next != null) { 40 p1.next = p1.next.next; 41 p.next = p.next.next; 42 p = p.next; 43 p1 = p1.next; 44 45 } 46 p1.next = null; 47 return head; 48 } 49 }