复杂链表的复制

来源:互联网 发布:js把毫秒数转换成日期 编辑:程序博客网 时间:2024/06/07 10:51


/** * Definition for singly-linked list with a random pointer. * class RandomListNode { *     int label; *     RandomListNode next, random; *     RandomListNode(int x) { this.label = x; } * }; */import java.util.HashMap;public class Solution {    public RandomListNode copyRandomList(RandomListNode head) {if(head == null)    return null;        HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();        RandomListNode cur = head;        RandomListNode headCopy = new RandomListNode(head.label),curCopy=headCopy;        map.put(cur, headCopy);        cur = cur.next;        while(cur != null){        RandomListNode temp = new RandomListNode(cur.label);        curCopy.next = temp;        curCopy = temp;        map.put(cur, curCopy);        cur = cur.next;               }        cur = head;        curCopy = headCopy;        while(cur != null){            if(cur.random!=null)        curCopy.random = map.get(cur.random);        cur = cur.next;        curCopy = curCopy.next;        }        return headCopy;    }}

题目描述


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.