Leetcode:Copy List with Random Pointer
来源:互联网 发布:卷皮网站源码 编辑:程序博客网 时间:2024/05/16 07:27
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.
1. 使用HashMap,记录源节点与新节点的对应关系,或者源节点与next的关系,或者源节点与random的关系。
2.直接在源节点后面复制源节点,random也是指向源节点random的next,然后分割链表即可。
代码:
/** * 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; RandomListNode dummy = new RandomListNode(0); RandomListNode node1 = head; RandomListNode node2 = dummy; HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>(); while(node1!=null) { RandomListNode copynode = new RandomListNode(node1.label); copynode.random = node1; node2.next = copynode; map.put(node1,node1.next); RandomListNode tmp = node1; node1 = node1.next; tmp.next = copynode; node2 = node2.next; } node2 = dummy.next; while(node2!=null) { if(node2.random.random!=null)node2.random = node2.random.random.next; else node2.random = null; node2 = node2.next; } node1 = head; while(node1!=null) { node1.next = map.get(node1); node1 = node1.next; } return dummy.next; }}
____________
| |
0——>1——>2——>3——>4——>5——>null
0 0
- [leetcode][list] Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode | Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode OJ:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode] - Copy List with Random Pointer
- Java 计算计算两个日期之间的间隔…
- Java 计算计算两个日期之间的间隔…
- 用 Calenar 获取日期
- 用 Calenar 获取日期
- 文件切割合并器 下载地址 及 帮助
- Leetcode:Copy List with Random Pointer
- 文件切割合并器 1 主类 SplitAnd…
- 文件切割合并器 2 切割类 Split
- 响应式布局如何测试不同分辨率
- 文件切割合并器 4 帮助类 Help
- 文件切割合并器 3 合并类Merge
- 文件切割合并器 5 关于类
- 文件切割合并器 6 GBC 简化
- 文件切割合并器 7 上层界面