138. Copy List with Random Pointer
来源:互联网 发布:订餐的软件 编辑:程序博客网 时间:2024/06/07 05:56
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.
/** * 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 head; RandomListNode node = head; while (node != null) { RandomListNode tmp = node.next; RandomListNode add = new RandomListNode(node.label); add.next = node.next; node.next = add; node = tmp; } node = head; while (node != null) { if (node.random != null) node.next.random = node.random.next; node = node.next.next; } RandomListNode dummy = new RandomListNode(0); RandomListNode cursor = dummy; node = head; while (node != null) { RandomListNode tmp = node.next.next; cursor.next = node.next; cursor = cursor.next; node.next = tmp; node = tmp; } return dummy.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 head; HashMap<RandomListNode, RandomListNode> map = new HashMap<>(); RandomListNode node = head; while (node != null) { map.put(node, new RandomListNode(node.label)); node = node.next; } node = head; while (node != null) { RandomListNode tmp = map.get(node); tmp.next = map.get(node.next); tmp.random = map.get(node.random); node = node.next; } return map.get(head); }}
0 0
- 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [Leetcode] 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [leetcode] 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- leetcode.138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- LeetCode-138.Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- [Leetcode]138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- 138. Copy List with Random Pointer
- [LeetCode] 138. Copy List with Random Pointer
- centos7 yum安装apache
- C语言中的运算符总结
- Spark RDD 二次分组排序取TopK
- Linux设备模型分析之kobject
- 如何利用Reactjs进行简单的表单验证
- 138. Copy List with Random Pointer
- UVA 10233 Dermuba Triangle
- java实现redis
- Codeforces Round #278 (Div. 1) B. Strip
- BZOJ P1041[HAOI2008]圆上的整点
- 设置Ubuntu系统的分辨率--解决vmware workstaion中shell窗口太小的问题
- C语言中运算符的总结
- POJ 1681 画家问题
- 项目实战篇-餐馆管理系统—MFC,PHP,MySql:6.订单管理模块