首页 > 代码库 > Copy List with Random Pointer
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.
思路
遍历list将所有节点new一个出来放到hashmap中,第二遍遍历list将旧的节点对应新节点取出来组成链表就okay了
1 /** 2 * Definition for singly-linked list with a random pointer. 3 * class RandomListNode { 4 * int label; 5 * RandomListNode next, random; 6 * RandomListNode(int x) { this.label = x; } 7 * }; 8 */ 9 import java.util.HashMap;10 import java.util.Map;11 12 public class Solution {13 public RandomListNode copyRandomList(RandomListNode head) {14 if(head == null)15 return head;16 Map<RandomListNode, RandomListNode> old2new = new HashMap<RandomListNode, RandomListNode>();17 18 //新的头结点19 RandomListNode newHead = new RandomListNode(head.label);20 old2new.put(head, newHead);21 22 RandomListNode tempHead = head.next; //所有的节点放到hashmap中23 while(tempHead != null){24 RandomListNode tempNode = new RandomListNode(tempHead.label);25 old2new.put(tempHead, tempNode);26 tempHead = tempHead.next;27 }//while28 29 RandomListNode tempNewHead = null;30 tempHead = head;31 32 while(tempHead != null){33 tempNewHead = old2new.get(tempHead);34 tempNewHead.next = old2new.get(tempHead.next);35 tempNewHead.random = old2new.get(tempHead.random);36 tempHead = tempHead.next;37 tempNewHead = tempNewHead.next;38 }//while39 40 return newHead;41 }42 }
Copy List with Random Pointer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。