一種特殊的單鏈表結點類描述如下:
class Node{
int value;
Node next;
Node rand;
Node(int v){
value=v;
}
}
rand指針是單鏈表結點結構中新增的指針,rand可能指向鏈表中的任意一個節點,也可能指向null,給定一個由Node節點類型組成的無環單鏈表的頭結點head,請實現一個函數完成這個鏈表的複製,並返回複製的新鏈表的頭結點。
package com.inspire.chapter6;
import java.util.HashMap;
public class Code04_CopyListWithRandom {
public static class Node {
public int value;
public Node next;
public Node rand;
public Node(int v) {
value = v;
}
}
// 方法一:用HashMap解決
public static Node copyListWithRand1(Node head) {
HashMap<Node, Node> map = new HashMap<>();
Node cur = head;
while (cur != null) {
map.put(cur, new Node(cur.value));
cur = cur.next;
}
cur = head;
while (cur != null) {
// cur 老
// map.get(cur) 新
map.get(cur).next = map.get(cur.next);
map.get(cur).rand = map.get(cur.rand);
cur = cur.next;
}
return map.get(head);
}
public static void main(String[] args) {
}
}