题目链接
Node
public class Node {
public int val;
public Node next;
public Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
创建带头节点的随机指针链表
public Node creatRandomNextList(Integer[][] arr) {
Node head = new Node(0);
if (arr.length == 0) {
return head;
}
Node curNode = head;
Map<Integer, Node> mp = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
Node newNode = new Node(arr[i][0]);
curNode.next = newNode;
curNode = curNode.next;
mp.put(i, curNode);
}
curNode.next = null;
curNode = head.next;
for (int i = 0; i < arr.length; i++) {
curNode.random = mp.get(arr[i][1]);
curNode = curNode.next;
}
return head;
}
打印不带头节点的随机指针链表
public void showNoHeadRandomNextList(Node head) {
Node curNode = head;
while (curNode != null) {
Integer randomVal = curNode.random == null ? null : curNode.random.val;
System.out.print("[" + curNode.val + " " + randomVal + "] ");
curNode = curNode.next;
}
System.out.println();
}
法一(哈希)
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Node curNode = head;
Map<Node, Node> mp = new HashMap<>();
while (curNode != null) {
Node copyNode = new Node(curNode.val);
mp.put(curNode, copyNode);
curNode = curNode.next;
}
curNode = head;
while (curNode != null) {
mp.get(curNode).next = mp.get(curNode.next);
mp.get(curNode).random = mp.get(curNode.random);
curNode = curNode.next;
}
return mp.get(head);
}
本地测试
lay.showTitle(138);
Solution138 sol138 = new Solution138();
Integer[][] arr138 = new Integer[][]{{7, null}, {13, 0}, {11, 4}, {10, 2}, {1, 0}};
randomNextList.Node head138 = randomNextListOpt.creatRandomNextList(arr138);
randomNextListOpt.showNoHeadRandomNextList(head138.next);
randomNextList.Node copyHead138 = sol138.copyRandomList(head138);
randomNextListOpt.showNoHeadRandomNextList(copyHead138.next);