您的位置:首页 > Web前端

【剑指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

 

  • 点赞
  • 收藏
  • 分享
  • 文章举报
Blog_pc 发布了66 篇原创文章 · 获赞 0 · 访问量 313 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: