class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } /** * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点, * 另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。 * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路
1、把链表的节点一个个复制出来
*/ public class Solution25 { public RandomListNode Clone(RandomListNode pHead) { if (pHead == null) { return null; } RandomListNode curr1 = pHead; RandomListNode curr2 = new RandomListNode(0); RandomListNode head = curr2; while (curr1 != null) { RandomListNode randomListNode = new RandomListNode(curr1.label); if (curr1.random!=null){ RandomListNode randomListNode1 = new RandomListNode(curr1.random.label); randomListNode.random = randomListNode1; } curr1 = curr1.next; curr2.next = randomListNode; curr2 = curr2.next; } return head.next; } }