您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)java復(fù)制多向鏈表的方法的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過來看看吧。
多向鏈表結(jié)構(gòu)如
public class Node{ public int value; public Node next; public Node rand; public Node(int data){ this.value = data; } }
方法一:使用HashMap結(jié)構(gòu)
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}; //數(shù)組轉(zhuǎn)Node Node head = array2node(array); Node help = head; System.out.print("處理前 "); while(help != null){ System.out.print(help.value + " "); help = help.next; } //使用HashMap結(jié)構(gòu) Node res = copyFromRand1(head); System.out.println(); System.out.print("處理后結(jié)果:"); while(res != null){ System.out.print(res.value+" "); res = res.next; } } //使用HashMap結(jié)構(gòu) 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); } //數(shù)組轉(zhuǎn)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; } //基礎(chǔ)node節(jié)點(diǎn)結(jié)構(gòu) public static class Node{ public int value; public Node next; public Node rand; public Node(int data){ this.value = data; } } }
2、使用幾個(gè)有效變量方法,無需其他結(jié)構(gòu)
//使用幾個(gè)有效變量方法 //替換方法一的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; }
感謝各位的閱讀!關(guān)于java復(fù)制多向鏈表的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。