# 剑指offer第二十五题复杂链表的复制

## 题目描述

package test;
class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
class Solution {
return null;
}

//1、复制每个结点，如复制结点A得到A1，将结点A1插到结点A后面；
while(currentNode != null){
RandomListNode cloneNode = new RandomListNode(currentNode.label);
RandomListNode nextNode = currentNode.next;
currentNode.next = cloneNode;
cloneNode.next = nextNode;
currentNode = nextNode;
}

//2、重新遍历链表，复制老结点的随机指针给新结点，如A1.random = A.random.next;
while(currentNode != null) {
currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
System.out.println(currentNode.next.random);
currentNode = currentNode.next.next;
}

//3、拆分链表，将链表拆分为原链表和复制后的链表
while(currentNode != null) {//currentNode = A
RandomListNode cloneNode = currentNode.next;//cloneNode = A'
currentNode.next = cloneNode.next;//A -> B
cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
currentNode = currentNode.next;
}

}
}
public class Main{
public static void main(String[] args) {
RandomListNode n1 = new RandomListNode(1);//804
RandomListNode n2 = new RandomListNode(3);//805
RandomListNode n3 = new RandomListNode(6);//806
RandomListNode n4 = new RandomListNode(4);//807
RandomListNode n5 = new RandomListNode(2);//808

n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
Solution solution = new Solution();
RandomListNode list1=solution.Clone(n1);
for(;list1 != null;){
System.out.print("->" + list1.label);
list1 = list1.next;
}

}
}


package test;

import java.util.HashMap;

class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
class Solution {
{
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
//第一次遍历 新建立节点
while(p != null){
RandomListNode newNode = new RandomListNode(p.label);
map.put(p, newNode);
p = p.next;
}
//第二次遍历 赋值映射关系
while(p != null){
RandomListNode node = map.get(p);//返回p对应的value
node.next = (p.next == null)?null: map.get(p.next);//node这个地址有next和random属性
node.random = (p.random == null)?null: map.get(p.random);
p = p.next;
}
//最后的返回值
}
}
public class Main{
public static void main(String[] args) {
RandomListNode n1 = new RandomListNode(1);//804
RandomListNode n2 = new RandomListNode(3);//805
RandomListNode n3 = new RandomListNode(6);//806
RandomListNode n4 = new RandomListNode(4);//807
RandomListNode n5 = new RandomListNode(2);//808

n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
Solution solution = new Solution();
RandomListNode list1=solution.Clone(n1);
for(;list1 != null;){
System.out.print("->" + list1.label);
list1 = list1.next;
}
}
}


06-05 141
06-19 185

04-18 71
05-17 45
10-20 498