算法刷题之路之链表初探(四)
算法刷题之路之链表初探(四)
今天来学习的算法题是leecode138随机链表的赋值,是一道简单的入门题,话不多说!直接上!
条件
代码
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Node cur = head;
HashMap<Node,Node> map = new HashMap<>();
while(cur!=null){
//建立新链表和旧链表的对应关系(1对1)
map.put(cur,new Node(cur.val));
cur = cur.next;
}
cur=head;
while(cur!=null){
//map.get(cur)是获取到新链表中的node节点。
//因为是一对以的对应关系,所以旧节点的next就等于新节点的next
//所以只需要拿到旧节点对应的next值赋值给新节点就完成了新节点的next属性的赋值
map.get(cur).next=map.get(cur.next);
//随机链表也是一样的道理
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
return map.get(head);
}
}
原文地址:https://blog.csdn.net/aoyuanyuan0921/article/details/140430979
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!