Copy List with Random Pointer
来源:互联网 发布:南京大学软件学院地址 编辑:程序博客网 时间:2024/06/10 16:20
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) { RandomListNode fake = new RandomListNode(0); fake.next = head; RandomListNode cur = fake; RandomListNode copyFake = new RandomListNode(0); RandomListNode copyCur = copyFake; Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); while(cur.next != null) { RandomListNode newNode = new RandomListNode(cur.next.label); map.put(cur.next, newNode); copyCur.next = newNode; copyCur = copyCur.next; cur = cur.next; } cur = fake.next; copyCur = copyFake.next; while (cur != null) { if (cur.random != null) { copyCur.random = map.get(cur.random); } cur = cur.next; copyCur = copyCur.next; } return copyFake.next; }}
一个不用 extra space的做法:http://blog.csdn.net/linhuanmars/article/details/22463599
把每一个新的node都加在原来node的后面,最后再分割出去:
public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return head; RandomListNode node = head; while(node!=null) { RandomListNode newNode = new RandomListNode(node.label); newNode.next = node.next; node.next = newNode; node = newNode.next; } node = head; while(node!=null) { if(node.random != null) node.next.random = node.random.next; node = node.next.next; } RandomListNode newHead = head.next; node = head; while(node != null) { RandomListNode newNode = node.next; node.next = newNode.next; if(newNode.next!=null) newNode.next = newNode.next.next; node = node.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
- Remove Duplicates from Sorted List II
- ubuntu系统下eclipse配置hadoop开发环境并运行wordcount程序
- Codeforces Round #257 (Div. 2)E(数论+构造)
- 关于 头文件引用...
- VC Static 背景图 文字刷新问题 解决方法
- Copy List with Random Pointer
- Turbo C/C++ for Windows 集成实验
- Libreoffice 是Openoffice的部分
- lua作配置文件
- JSCompress不是插件,Ta不挑编辑器,支持所有编辑器
- 数据库详解与介绍 System.Data.SQLite
- Master Page Path MasterPage 相对路径
- 水题 攒人品
- ASDFASDFASD