138. Copy List with Random Pointer
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */ public class Solution { public RandomListNode copyRandomList(RandomListNode head) { RandomListNode dummy = new RandomListNode(0); RandomListNode cur = dummy; HashMap<RandomListNode, RandomListNode> map = new HashMap<>(); while( head != null){ if(!map.containsKey(head)){ map.put( head, new RandomListNode(head.label)); } cur.next = map.get(head); if(head.random!= null){ if(!map.containsKey(head.random)){ map.put(head.random, new RandomListNode(head.random.label)); } cur.next.random = map.get(head.random); } cur = cur.next; head = head.next; } return dummy.next; } }
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.
posted on 2018-07-18 09:37 猪猪🐷 阅读(101) 评论(0) 收藏 举报
浙公网安备 33010602011771号