您的位置:首页 > 运维架构

Copy List with Random Pointer

2015-10-27 21:37 375 查看
题目:

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.

不要想的太复杂了。直接用个hashMap存储原始结点和copy的结点的对应关系。

先把结点整个从头到尾进行复制。然后从头到尾复制它的random

/**
* 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) {
Map<RandomListNode,RandomListNode> map = new HashMap<>();
RandomListNode p = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode q = dummy;
while(p!=null) {
q.next = new RandomListNode(p.label);
map.put(p,q.next);
p = p.next;
q = q.next;
}
p = head;
q = dummy.next;
while(p!=null) {
q.random = map.get(p.random);
p = p.next;
q = q.next;
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: