Copy List With Random Pointer
来源:互联网 发布:淘宝商业摄影需要器材 编辑:程序博客网 时间:2024/05/23 13:22
使用HashTable
/** * 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 dummy1 = new RandomListNode(-1); RandomListNode dummy2 = new RandomListNode(-1); dummy1.next = head; RandomListNode ptr1 = dummy1, ptr2 = dummy2; Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); while (ptr1.next != null) { ptr1 = ptr1.next; ptr2.next = new RandomListNode(ptr1.label); ptr2 = ptr2.next; map.put(ptr1, ptr2); } ptr2.next = null; ptr1 = dummy1; ptr2 = dummy2; while (ptr1.next != null) { ptr1 = ptr1.next; map.get(ptr1).random = map.get(ptr1.random); } return dummy2.next; }}
不使用HashTable
/** * 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 ptr = head; while (ptr != null) { RandomListNode copy = new RandomListNode(ptr.label); copy.next = ptr.next; ptr.next = copy; ptr = copy.next; } ptr = head; while (ptr != null) { if (ptr.random != null) { ptr.next.random = ptr.random.next; } ptr = ptr.next.next; } ptr = head; RandomListNode newHead = head.next; while (ptr != null) { RandomListNode temp = ptr.next; ptr.next = temp.next; if (temp.next != null) { temp.next = temp.next.next; } ptr = ptr.next; } return newHead; }}
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
- iOS开发 贝塞尔曲线
- WinDBG基础----了解Symbols
- 关于模板和函数传参
- Makefile函数集
- WM_ACTIVATE
- Copy List With Random Pointer
- iPhone屏幕尺寸、分辨率及适配
- 黑马程序员-IOS基础之OC分类(Category)
- sublime text2 常用安装包
- ios-AFNetworking2.5
- Beaglebone black eMMC烧写脚本debrick.s分析
- 消灭编译警告(Warning)
- 快速排序
- WIN7 下 explorer 进行的文件移动COPY HOOK