Copy List with Random Pointer
来源:互联网 发布:想做淘宝做什么比较好 编辑:程序博客网 时间:2024/05/05 03:23
Q:
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.
Solution:
/** * 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) { if (head == null) return null; HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); RandomListNode ret = new RandomListNode(head.label); map.put(head, ret); RandomListNode cur = head; while (cur != null) { RandomListNode temp = map.get(cur); if (temp == null) continue; if (cur.next != null) { RandomListNode newNext = map.get(cur.next); if (newNext != null) { temp.next = newNext; } else { newNext = new RandomListNode(0); newNext.label = cur.next.label; temp.next = newNext; map.put(cur.next, newNext); } } if (cur.random != null) { RandomListNode newRandom = map.get(cur.random); if (newRandom != null) { temp.random = newRandom; } else { newRandom = new RandomListNode(0); newRandom.label = cur.random.label; temp.random = newRandom; map.put(cur.random, newRandom); } } cur = cur.next; } return ret; }}
0 0
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Android杀毒原理
- ASCII码点阵字库的显示
- U3D DotH教程
- POJ 2253 Frogger
- 第九周项目6-穷举法之年龄几何
- Copy List with Random Pointer
- Java中的destructor
- 深入理解java异常处理机制
- hdu 1051 贪心
- ASCII字符点阵字库的制作和使用
- java生产者消费者问题
- Python核心编程 第二版 第二章 部分习题解答
- 听君一席话
- VC++几种定时器使用方法的归纳