剑指offer算法题
链表
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。
题目分析
- 解题思路:
- 1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
- 2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
- 3、拆分链表,将链表拆分为原链表和复制后的链表
下面是Java代码
/*
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 tmpHead = new RandomListNode(pHead.label);
RandomListNode tmp = pHead;
//1、复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
while(tmp!=null){
RandomListNode cloneNode = new RandomListNode(tmp.label);
RandomListNode nextNode = tmp.next;
tmp.next = cloneNode;
cloneNode.next = nextNode;
tmp = nextNode;
}
tmp = pHead;
//2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
while(tmp!=null){
tmp.next.random = tmp.random==null? null: tmp.random.next;
tmp = tmp.next.next;
}
tmp = pHead;
RandomListNode pNewHead = pHead.next;
//3、拆分链表,将链表拆分为原链表和复制后的链表
while(tmp!=null){
RandomListNode cloneNode = tmp.next;
tmp.next = cloneNode.next;
cloneNode.next = cloneNode.next ==null?null:cloneNode.next.next;
tmp = tmp.next;
}
return pNewHead;
}
}