(视频教程推荐:java课程)
public class node{ public int value; public node next; public node rand; public node(int data){ this.value = data; }}
方法一:使用hashmap结构
public class copyfrommultinode { public static void main(string[] args){ int[] array = {12,3,4,5,6,77,6,54,56,6,7,87,15,15,15}; //数组转node node head = array2node(array); node help = head; system.out.print("处理前 "); while(help != null){ system.out.print(help.value + " "); help = help.next; } //使用hashmap结构 node res = copyfromrand1(head); system.out.println(); system.out.print("处理后结果:"); while(res != null){ system.out.print(res.value+" "); res = res.next; } } //使用hashmap结构 public static node copyfromrand1(node head){ node cur = head; hashmap<node, node> map = new hashmap<>(); while(cur != null){ map.put(cur, new node(cur.value)); cur = cur.next; } cur = head; while(cur != null){ map.get(cur).next = map.get(cur.next); map.get(cur).rand = map.get(cur.rand); cur = cur.next; } return map.get(head); } //数组转node功能,供测试使用 public static node array2node(int[] array){ node head = new node(array[0]); node cur = head; for(int i=1; i<array.length; i++){ cur.next = new node(array[i]); cur = cur.next; } return head; } //基础node节点结构 public static class node{ public int value; public node next; public node rand; public node(int data){ this.value = data; } }}
2、使用几个有效变量方法,无需其他结构
//使用几个有效变量方法 //替换方法一的copyfromrand1方法 public static node copyfromrand2(node head){ node next = null; node cur = head; //1 -> 2 -> 3 -> 4 ==> 1 -> 1` -> 2 -> 2` -> 3 -> 3` -> 4 -> 4 //完成链表拼接 while(cur != null){ next = cur.next; cur.next = new node(cur.value); cur.next.next = next; cur = next; } cur = head; node curcopy = null; //添加node的rand值 while(cur != null){ next = cur.next.next; curcopy = cur.next.next; curcopy = cur.rand != null? cur.rand.next: null; cur = next; } node res = head.next; cur = head; //拆分 // 1 -> 1` -> 2 -> 2` -> 3 -> 3` -> 4 -> 4 // ==> 1 -> 2 -> 3 -> 4 和 1`-> 2`-> 3`-> 4` while(cur != null){ next = cur.next.next; curcopy = cur.next; cur.next = next; curcopy.next = next != null ? next.next:null; cur = next; } return res; }
相关教程推荐:java入门
以上就是java复制多向链表的方法的详细内容。
