算法總結之 復制含有隨機指針節點的鏈表
阿新 • • 發佈:2017-09-10
logs != imp 使用 turn ret 哈希表 算法 可能
一種特殊的鏈表節點類描述如下:
public class Node{
public int value;
public Node next;
public Node rand;
public Node(int data){
this.value = data
}
}
rand指針是Node類中的新增的指針,這個指針可能指向鏈表中任意的一個節點,也可能指向null
首先介紹普通解法:
使用哈希表
首先從左到右遍歷鏈表,對每個節點都復制生成相應的副本節點
key 1 value 1`
package TT; import java.util.HashMap;public class Test95 { public class Node{ public int value; public Node next; public Node rand; public Node(int data){ this.value=data; } } public Node copyListWithRand1(Node head){ HashMap<Node, Node> map=new HashMap<Node, Node>(); Node cur=head; 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); } }
算法總結之 復制含有隨機指針節點的鏈表