您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關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復制多向鏈表的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。