一种特殊的单链表结点类描述如下:
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) {
}
}