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

Leetcode-Copy List with Random Pointer

2014-12-12 02:47 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.

Solution:

/**
* 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,RandomListNode>();
if (head==null) return null;

RandomListNode head2 = new RandomListNode(head.label);
map.put(head,head2);
RandomListNode cur = head2;

while (head!=null){
RandomListNode rand1 = head.random;
if (rand1!=null && map.containsKey(rand1)){
cur.random = map.get(rand1);
} else if (rand1!=null) {
RandomListNode rand2 = new RandomListNode(rand1.label);
map.put(rand1,rand2);
cur.random = rand2;
}

if (head.next==null){
cur.next=null;
} else {
RandomListNode next = head.next;
if (map.containsKey(next))
cur.next = map.get(next);
else {
RandomListNode next2 = new RandomListNode(next.label);
cur.next = next2;
map.put(next,next2);
}
}

head = head.next;
cur = cur.next;
}

return head2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: