阿里终面在线编程题,写出来与大家分享一下
有一个单向链表,每个节点都包含一个random指针,指向本链表中的某个节点或者为空,写一个深度拷贝函数,拷贝整个链表,包括random指针。尽可能考虑可能的异常情况。
算法如下:
/*
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)
{
copyNodes(pHead);
setClonedNodes(pHead);
return splitNodes(pHead);
}
//第一步,复制链表任意结点N并创建新结点N‘,再把N'链接到N的后面
public static void copyNodes(RandomListNode head){
RandomListNode temp = head;
while(temp!=null){
RandomListNode clonedNode = new RandomListNode(0);
clonedNode.next = temp.next;
clonedNode.label = temp.label;
clonedNode.random = null;
temp.next = clonedNode;
temp = clonedNode.next;
}
}
//第二步,设置复制出来的结点
public static void setClonedNodes(RandomListNode head){
RandomListNode pNode = head;
while(pNode!=null){
RandomListNode pCloned = pNode.next;
if(pNode.random!=null){
pCloned.random = pNode.random.next;
}
pNode = pCloned.next;
}
}
//第三步,将第二步得到的链表拆分成两个链表
public static RandomListNode splitNodes(RandomListNode head){
RandomListNode pNode = head;
RandomListNode clonedHead = null;
RandomListNode clonedNode = null;
if(pNode!=null){
clonedHead = pNode.next;
clonedNode = pNode.next;
pNode.next = clonedNode.next;
pNode = pNode.next;
}
while(pNode!=null){
clonedNode.next = pNode.next;
clonedNode = clonedNode.next;
pNode.next = clonedNode.next;
pNode = pNode.next;
}
return clonedHead;
}
}
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环