标签:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。
分三步(分而治之)
/*
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)
{
cloneNodes(pHead);
cloneRandom(pHead);
return reconnectNode(pHead);
}
// 复制链表追加到每个元素的后面
public void cloneNodes(RandomListNode pHead) {
RandomListNode temp = pHead;
while (temp != null) {
RandomListNode newNode = new RandomListNode(temp.label);
newNode.random = null;
newNode.next = temp.next;
temp.next = newNode;
temp = newNode.next;
}
}
// 复制每个元素的random指针
public void cloneRandom(RandomListNode pHead) {
RandomListNode temp = pHead;
while (temp != null) {
if (temp.random != null) {
temp.next.random = temp.random.next;
} else {
temp.next.random = null;
}
temp = temp.next.next;
}
}
// 从整个链表中抽离出来我们复制的链表
public RandomListNode reconnectNode(RandomListNode pHead) {
RandomListNode pNode = pHead;
RandomListNode newHead = null;
RandomListNode newNode = null;
if (pNode != null) {
newHead = pNode.next;
newNode = newHead;
pNode.next = newNode.next;
pNode = pNode.next;
}
while (pNode != null) {
newNode.next = pNode.next;
newNode = newNode.next;
pNode.next = newNode.next;
pNode = pNode.next;
}
return newHead;
}
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5628198.html