Copy List with Random Pointer

来源:互联网 发布:手机淘宝怎样朋友代付 编辑:程序博客网 时间:2024/06/15 17:41

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.

/** * 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;        RandomListNode newHead=new RandomListNode(head.label);        Map<RandomListNode,RandomListNode> map=new HashMap<RandomListNode,RandomListNode>();        map.put(head,newHead);        RandomListNode node=head.next;        RandomListNode p=newHead;        while(node!=null){            RandomListNode copy=new RandomListNode(node.label);            p.next=copy;            p=p.next;            map.put(node,p);            node=node.next;        }        node=head;        while(node!=null){            map.get(node).random=map.get(node.random);            node=node.next;        }                return newHead;    }}
思路:1、复制原链表上的每个节点,把<node,newnode>的陪对信息放入HashMap中;2、根据哈希表复制Random节点

0 0
原创粉丝点击