您现在的位置是:首页>爱编程>详细内容
25.复杂链表的复制
发布时间:2018-08-22 00:00:00编辑:Jason浏览(296)评论(0)
25.复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
解题思路:
1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
3、拆分链表,将链表拆分为原链表和复制后的链表
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;
//Clone RandomListNode
RandomListNode pNode = pHead;
while(pNode != null){
RandomListNode pCloned = new RandomListNode(pNode.label);
pCloned.next = pNode.next;
pCloned.random = null;
pNode.next = pCloned;
pNode = pCloned.next;
}
//
pNode = pHead;
while(pNode != null){
RandomListNode pCloned = pNode.next;
if(pNode.random != null)
pCloned.random = pNode.random.next;
pNode = pCloned.next;
}
//seperate two list
pNode = pHead;
RandomListNode pClonedHead = null;
RandomListNode pCloned = null;
if(pNode != null){
pClonedHead = pCloned = pNode.next;
pNode.next = pCloned.next;
pNode = pNode.next;
}
while(pNode != null){
pCloned.next = pNode.next;
pCloned = pCloned.next;
pNode.next = pCloned.next;
pNode = pNode.next;
}
return pClonedHead;
}
}
关键字词:offer
上一篇:二叉树中和为某一值的路径
下一篇:26.二叉搜索树与双向链表