题目链接:
JZ25 复杂链表的复制
本题思路:
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
// base case
if(pHead == null) return pHead;
// 链表节点的复制
// cur = cur.next.next跳到原链表下一个节点
for(RandomListNode cur = pHead, copy = null; cur != null; cur = cur.next.next) {
copy = new RandomListNode(cur.label); // 传入节点的值
copy.next = cur.next; // 交接右侧指针
cur.next = copy; // 交接左侧指针
}
// 拷贝链表的随机指针复制
for(RandomListNode cur = pHead; cur != null; cur = cur.next.next) {
if(cur.random != null) {
cur.next.random = cur.random.next; // 在拷贝链表上操作 画图易理解
}
}
// 分离出拷贝链表
RandomListNode cur = pHead;
RandomListNode copyHead = pHead.next;
RandomListNode temp = null;
// 逐个后移 当最后一个拷贝节点复制给cur
// cur != null但cur.next == null 此时结束分离
while(cur != null && cur.next != null) {
temp = cur.next; // 拷贝链表从pHead.next向下传递
cur.next = temp.next; // 原链表向下传递
cur = temp; // 逐个后移
}
return copyHead;
}
}