题目:复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
解题思路:
(1) 根据原始链表的每个节点N创建对应的N‘。把N’链接在N后面。
(2) 如果原始链表的节点N的random指向S,则它对应的肤质节点N‘的random应该指向S的下一个节点S’。
(3)把这个长链表拆分为两个链表:奇数位置为原链表。偶数位置连起来是复制链表
代码实现:
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
import java.util.*;
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null){
return null;
}
//A-A'-B-B'
//进行链表的复制
RandomListNode cur=pHead;
while(cur!=null) {
RandomListNode cloneNode=new RandomListNode(cur.label);
cloneNode.next=cur.next;
cur.next=cloneNode;
cur=cloneNode.next;
}
//复制链表的random指针
cur=pHead;
while(cur!=null) {
cur.next.random=cur.random==null?null:cur.random.next;
cur=cur.next.next;
}
//进行奇偶拆分
RandomListNode oddN=pHead;
RandomListNode evenN=pHead.next;
RandomListNode even=evenN;
while(even!=null) {
oddN.next=oddN.next.next;
even.next=even.next==null?null:even.next.next;
oddN=oddN.next;
even=even.next;
}
return evenN;
}
}