描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。 下图是一个含有5个结点的复杂链表。图中实线箭头表示next指针,虚线箭头表示random指针。为简单起见,指向null的指针没有画出。
示例:
输入:{1,2,3,4,5,3,5,#,2,#}
输出:{1,2,3,4,5,3,5,#,2,#}
解析:我们将链表分为两段,前半部分{1,2,3,4,5}为ListNode,后半部分{3,5,#,2,#}是随机指针域表示。
以上示例前半部分可以表示链表为的ListNode:1->2->3->4->5
后半部分,3,5,#,2,#分别的表示为
1的位置指向3,2的位置指向5,3的位置指向null,4的位置指向2,5的位置指向null
如下图:
示例1
输入: {1,2,3,4,5,3,5,#,2,#}
返回值: {1,2,3,4,5,3,5,#,2,#}
思路
遍历三遍
- 遍历第一遍 复制结点至原结点后边,使得 A->B->NULL 变成 A->A`->B->B`->NULL
- 遍历第二遍 复制随机指针
- 遍历第三遍 分开链表
代码
/*
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 pHead;
}
//遍历第一遍 复制结点至原结点后边
//使得 A->B->NULL 变成 A->A`->B->B`->NULL
RandomListNode cur = pHead;
while(cur != null) {
RandomListNode temp = new RandomListNode(cur.label);
temp.next = cur.next;
cur.next = temp;
cur = temp.next;
}
//遍历第二遍 复制随机指针
cur = pHead;
while(cur != null) {
RandomListNode temp = cur.next;
//随机指针可能为null
if (cur.random != null) {
temp.random = cur.random.next;
}
cur = temp.next;
}
//遍历第三遍 分开链表
cur = pHead;
RandomListNode res = pHead.next;
while(cur != null) {
RandomListNode temp = cur.next;
cur.next = temp.next;
if (temp.next != null) {
temp.next = temp.next.next;
}
cur = cur.next;
}
return res;
}
}