Leetcode Copy List with Random Pointer 拷贝链表
2015-05-08 17:02
344 查看
题目:
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记录原来的节点和拷贝的节点的对应关系。2. 再次遍历链表,把拷贝的节点连接起来,并加上random节点的关系。
Java代码实现:
/*** 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> nodes = new HashMap<RandomListNode, RandomListNode>();
RandomListNode node = head;
RandomListNode newHead = new RandomListNode(head.label);
nodes.put(node, newHead);
node = node.next;
while(node!=null)
{
nodes.put(node, new RandomListNode(node.label));
node = node.next;
}
node = head;
RandomListNode temp = newHead;
temp.random = nodes.get(node.random);
while(node!=null)
{
temp.next = nodes.get(node.next);
node = node.next;
temp = temp.next;
if(temp!=null)
temp.random = nodes.get(node.random);
}
return newHead;
}
}
相关文章推荐
- LeetCode(Copy List with Random Pointer) 复杂链表的深拷贝
- [LeetCode] Copy List with Random Pointer 拷贝带有随机指针的链表
- LeetCode——Copy List with Random Pointer(带random引用的单链表深拷贝)
- 【LeetCode-面试算法经典-Java实现】【138-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(赋值带有随机指针的链表)
- LeetCode138 Copy List with Random Pointer(深度复制带有随机指针的链表) Java题解
- LeetCode----Copy List with Random Pointer 深度拷贝,浅度拷贝,Lazy拷贝解析
- [LeetCode]Copy List with Random Pointer &Clone Graph 复杂链表的复制&图的复制
- Copy List with Random Pointer 复制有随机指针的链表@LeetCode
- LeetCode之复制有random指针的链表Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer &Clone Graph 复杂链表的复制&图的复制
- 附有随机结点指针的链表的深度拷贝 Copy List with Random Pointer
- 【LeetCode-面试算法经典-Java实现】【143-Copy List with Random Pointer(有随机指针的链表复制)】
- Copy List with Random Pointer (leetcode)
- LeetCode[Linked List]: Copy List with Random Pointer