输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
/*
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
null;
RandomListNode head =
new RandomListNode(pHead.label);
RandomListNode temp = head;
while(pHead.
next !=
null)
{
temp.
next =
new RandomListNode(pHead.
next.label);
if(pHead.random !=
null)
{
temp.random =
new RandomListNode(pHead.random.label);
}
pHead = pHead.
next;
temp = temp.
next;
}
return head;
}
}
/*
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);
ConnectRandomNodes(pHead);
return ReConnectNodes(pHead);
}
public void CloneNodes(RandomListNode pHead)
{
RandomListNode pNode = pHead;
while(pNode !=
null)
{
RandomListNode pCloned =
new RandomListNode(pNode.label);
pCloned.
next = pNode.
next;
pNode.
next = pCloned;
pNode = pCloned.
next;
}
}
public void ConnectRandomNodes(RandomListNode pHead)
{
RandomListNode pNode = pHead;
while(pNode !=
null)
{
RandomListNode pCloned = pNode.
next;
if(pNode.random !=
null)
{
pCloned.random = pNode.random.
next;
}
pNode = pCloned.
next;
}
}
public RandomListNode ReConnectNodes(RandomListNode pHead)
{
RandomListNode pNode = pHead;
RandomListNode pClonedHead =
null;
RandomListNode pClonedNode =
null;
if(pNode !=
null)
{
pClonedHead = pNode.
next;
pClonedNode = pNode.
next;
pNode.
next = pClonedNode.
next;
pNode = pNode.
next;
}
while(pNode !=
null)
{
pClonedNode.
next = pNode.
next;
pClonedNode = pClonedNode.
next;
pNode.
next = pClonedNode.
next;
pNode = pNode.
next;
}
return pClonedHead;
}
}
转载请注明原文地址: https://ju.6miu.com/read-1138584.html