Keywords: Java

Test point: decomposition makes complex problems simple

Title Description

Enter a complex linked list (each node has a node value, and two pointers, one to the next node, and another special pointer random to a random node). Please make a deep copy of this linked list and return the copied head node. (Note: please do not return the node reference in the parameter in the output result, otherwise the problem determination program will directly return null)

Solutions to problems

Source: niuke.com

/*
*Solutions:
*1. Traverse the list and copy each node. For example, copy node a to get A1, and insert node A1 after node a;
*2. Traverse the linked list again, copy the random pointer of the old node to the new node, such as A1.random = A.random.next;
*3. Split the linked list into the original one and the copied one
*/

```/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;

RandomListNode(int label) {
this.label = label;
}
}
*/

public class Solution {
return null;
}

//1,Copy each node, such as a copy node A obtain A1，The node A1 Insert to node A Back;
while(currentNode != null){
RandomListNode cloneNode = new RandomListNode(currentNode.label);
RandomListNode nextNode = currentNode.next;
currentNode.next = cloneNode;
cloneNode.next = nextNode;
currentNode = nextNode;
}

//2,Traverse the linked list again, copy the random pointer of the old node to the new node, such as A1.random = A.random.next;
while(currentNode != null) {
currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
currentNode = currentNode.next.next;
}

//3,Split the linked list into the original one and the copied one
while(currentNode != null) {
RandomListNode cloneNode = currentNode.next;
currentNode.next = cloneNode.next;
cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
currentNode = currentNode.next;
}