【剑指Offer】25、复杂链表的复制
2020-03-31 19:42
686 查看
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
题解:Hashmap
1 public static RandomListNode Clone(RandomListNode pHead){ 2 if(pHead==null){ 3 return pHead; 4 } 5 RandomListNode oldP= pHead; 6 RandomListNode freshP = pHead; 7 //用一个 hashmap 建立新旧链表节点的对应的结点关系 8 HashMap<RandomListNode, RandomListNode> map = new HashMap<>(); 9 //迭代旧链表,在 hashmap 中更新新链表的节点值字段 10 while(oldP!=null){ 11 map.put(oldP, new RandomListNode(oldP.label)); 12 oldP = oldP.next; 13 } 14 //更新新链表的 next 与 random 两个字段 15 while (freshP != null) { 16 if (freshP.next != null) { 17 map.get(freshP).next = map.get(freshP.next); 18 } else { 19 map.get(freshP).next = null; 20 } 21 map.get(freshP).random = map.get(freshP.random); 22 freshP = freshP.next; 23 } 24 return map.get(pHead); 25 }
初始化链表:
1 public static class RandomListNode { 2 int label; 3 RandomListNode next = null; 4 RandomListNode random = null; 5 RandomListNode(int label) { 6 this.label = label; 7 } 8 }
测试:
1 public static void main(String[] args) { 2 int[] nodes={1,2,3,4,5,3,5,-1,2,-1}; 3 int len=nodes.length; 4 RandomListNode head=new RandomListNode(nodes[0]); 5 RandomListNode temp=head; 6 for(int i=1;i<len;i++){ 7 temp.next=new RandomListNode(nodes[i]); 8 temp=temp.next; 9 } 10 RandomListNode listNode = Clone(head); 11 while (listNode!=null){ 12 System.out.print(listNode.label+" "); 13 listNode=listNode.next; 14 } 15 } 16 输出:1 2 3 4 5 3 5 -1 2 -1
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 剑指offer题解C++【25】复杂链表的复制
- [剑指Offer] 25.复杂链表的复制
- 剑指Offer——(25)复杂链表的复制
- 【剑指offer】25.复杂链表的复制[by Python]
- 剑指offer-25-js-复杂链表的复制
- 剑指offer-25.复杂链表的复制
- 【剑指offer-解题系列(25)】复杂链表的复制
- 剑指Offer_25_复杂链表的复制
- (C++)剑指offer-25:复杂链表的复制(分解让复杂问题简单)(再理解)
- 剑指offer之面试题25:复杂链表的复制
- 【剑指offer】25复杂链表的复制
- 剑指offer-25-复杂链表的复制
- js剑指offer-25-复杂链表的复制
- 剑指offer第二十五题【复杂链表的复制】c++实现
- 2.10 剑指offer 复杂链表的复制
- 剑指offer之复杂链表的复制(java)
- 剑指offer复杂链表复制
- 剑指offer-24-复杂链表的复制
- 剑指offer:复杂链表的复制(java)
- 剑指offer 面试题26复杂链表的复制