Copy List with Random Pointer

来源:互联网 发布:想做淘宝做什么比较好 编辑:程序博客网 时间:2024/05/05 03:23

Q:

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) {        if (head == null) return null;        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();        RandomListNode ret = new RandomListNode(head.label);        map.put(head, ret);        RandomListNode cur = head;        while (cur != null) {            RandomListNode temp = map.get(cur);            if (temp == null) continue;            if (cur.next != null) {                RandomListNode newNext = map.get(cur.next);                if (newNext != null) {                    temp.next = newNext;                }                else {                    newNext = new RandomListNode(0);                    newNext.label = cur.next.label;                    temp.next = newNext;                    map.put(cur.next, newNext);                }            }            if (cur.random != null) {                RandomListNode newRandom = map.get(cur.random);                if (newRandom != null) {                    temp.random = newRandom;                }                else {                    newRandom = new RandomListNode(0);                    newRandom.label = cur.random.label;                    temp.random = newRandom;                    map.put(cur.random, newRandom);                }            }            cur = cur.next;        }        return ret;    }}


0 0
原创粉丝点击