题解 | #复杂链表的复制#
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
import java.util.ArrayList;
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
int ListLength = getNodeLength(pHead, 0);
if (ListLength == 0) return null;
ArrayList<RandomListNode> list = ListNodeParseToList(pHead, ListLength, 0);
ArrayList<RandomListNode> r_list = storageRandomNode(pHead);
RandomListNode copyNode = null;
RandomListNode copyNodeHead = null;
for (int i = 0; i < ListLength; i++) {
if (i == 0) {
copyNode = new RandomListNode(list.get(i).label);
copyNodeHead = copyNode;
}
try {
if ((i + 1) <= ListLength) {
copyNode.next = new RandomListNode(list.get(i + 1).label);
}
} catch (Exception e) {
}
if (r_list.get(i) == null) {
copyNode.random = null;
} else {
copyNode.random = new RandomListNode(r_list.get(i).label);
}
copyNode = copyNode.next;
}
return copyNodeHead;
}
public int getNodeLength(RandomListNode node, int length) {
while (node != null) {
node = node.next;
length++;
}
return length;
}
public <T> ArrayList<T> ListNodeParseToList(RandomListNode head, int length,
int start) {
ArrayList list = new ArrayList();
while (start != 0) {
head = head.next;
start--;
}
for (int i = 0; i < length; i++) {
list.add(head);
try {
head = head.next;
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public <T> ArrayList<T> storageRandomNode(RandomListNode node) {
ArrayList list = new ArrayList();
while (node != null) {
list.add(node.random);
node = node.next;
}
return list;
}
}
