[JAVA]deep copy链表
生活随笔
收集整理的這篇文章主要介紹了
[JAVA]deep copy链表
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
deep copy的意思我覺得就是復(fù)制一個(gè)對象成為新的對象,和原來的對象有不同的內(nèi)存地址,不是簡單的引用復(fù)制。
題目來源:leetcode
題目描述:
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.
最簡單的辦法就是先把所有都復(fù)制一遍,然后重新給他的next和radom賦值。實(shí)際上直接在當(dāng)前結(jié)點(diǎn)的后面復(fù)制會(huì)比在map中復(fù)制更加快,但是放到map感覺更加形象的解釋deepcopy的概念
?
/* // Definition for a Node. class Node {public int val;public Node next;public Node random;public Node() {}public Node(int _val,Node _next,Node _random) {val = _val;next = _next;random = _random;} }; */ class Solution {public Node copyRandomList(Node head) {Map<Node,Node> m=new HashMap<Node,Node>();Node cur=head;while(cur!=null){m.put(cur,new Node(cur.val,null,null));cur=cur.next;}cur=head;while(cur!=null){m.get(cur).next=m.get(cur.next);m.get(cur).random=m.get(cur.random);cur=cur.next;}return m.get(head);} }?
轉(zhuǎn)載于:https://www.cnblogs.com/cuphoria/p/10547249.html
總結(jié)
以上是生活随笔為你收集整理的[JAVA]deep copy链表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Gnu/Linux 链接XServer方
- 下一篇: C# .NET Web API 如何自訂