leetcode138: Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
//import java.util.HashMap;
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null) return null;
//儲存各節點random指標位置
HashMap<RandomListNode,RandomListNode> map=new HashMap<RandomListNode,RandomListNode>();
RandomListNode pp=head;//儲存頭結點
while(head!=null){
map.put(head, head.random);
head=head.next;
}
//深度複製
head=pp;//回到頭結點
RandomListNode p=head.next;
RandomListNode pre=head;//用於連線連結串列, 先不管新連結串列的頭節點的random指標,等到其他節點指標指好後,在考慮它。
RandomListNode one=pre;//儲存新連結串列的頭結點
while(p!=null){//從第二個節點開始複製,需要保留前一個指標,你懂的。
RandomListNode lnode=new RandomListNode(p.label);
pre.next=lnode;
lnode.next=null;
lnode.random=map.get(p);//這塊很重要,要知道從哪裡獲得random指標。
pre=lnode;//最終pre是最後一個節點
p=p.next;
}
one.random=map.get(head);
return one;
}
}
相關文章
- LeetCode138:Copy List with Random PointerLeetCoderandom
- Leetcode Copy List with Random PointerLeetCoderandom
- Leetcode-Copy List with Random PointerLeetCoderandom
- Copy List with Random Pointer leetcode javarandomLeetCodeJava
- LeetCode 138. Copy List with Random PointerLeetCoderandom
- 【Leetcode】138. Copy List with Random PointerLeetCoderandom
- LeetCode 138:複製帶隨機指標的連結串列 Copy List with Random PointerLeetCode隨機指標random
- LeetCode 382 Linked List Random NodeLeetCoderandom
- LeetCode-Linked List Random NodeLeetCoderandom
- Copy of a Copy of a Copy
- C++ pointerC++
- AP(Access Pointer)
- opencv遇到NULL pointer(NULL array pointer is passed) 解決方案OpenCVNull
- Tagged Pointer 字串字串
- Null pointer (NULL array pointer is passed) in function cvGetMat, 報這樣的錯NullFunction
- random 模組random
- Random和Math.random()簡單總結random
- pointer-events屬性
- Math.random()random
- Math.randomrandom
- random()函式random函式
- dbms_randomrandom
- CSS3 pointer-eventsCSSS3
- SMART POINTER(智慧指標) (轉)指標
- PostgreSQL:COPYSQL
- 區分copy構造與copy賦值賦值
- 【DBMS_RANDOM】使用 DBMS_RANDOM包生成隨機字串random隨機字串
- python random模組Pythonrandom
- np.random.choicerandom
- DBMS_RANDOM使用random
- 測試random類random
- different random numbers generatorrandom
- 11 random案例1random
- Random 類的使用random
- golang unsafe.Pointer與uintptrGolangUI
- error:dereferencing pointer to incomplete typeError
- 採用Tagged Pointer的字串字串
- [CareerCup] 13.8 Smart Pointer 智慧指標指標