本文共 1099 字,大约阅读时间需要 3 分钟。
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.
在循环建立新链表的时候,用一个hashmap存入所有新建的点。再用一个循环遍历原链表,补充新链表的random结点。但是这样只能用于结点没有重复的val
class Solution { public Node copyRandomList(Node head) { if(head == null) { return head; } HashMapmap = new HashMap<>(); Node res = new Node(head.val, null, null); Node resHead = res; map.put(resHead.val, resHead); Node temp = head.next; while(temp != null) { Node node = new Node(temp.val, null, null); map.put(node.val, node); resHead.next = node; resHead = resHead.next; temp = temp.next; } resHead = res; while(head != null) { if(head.random != null) { resHead.random = map.get(head.random.val); } head = head.next; resHead = resHead.next; } return res; }}
为了解决重复val的问题,hashmap的key应该是老的结点
转载地址:http://cyqvb.baihongyu.com/