lintcode-medium-Copy List with Random Pointer

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Copy List with Random Pointer相关的知识,希望对你有一定的参考价值。

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建立新旧节点的对应关系,再把random pointer加入,这样可以保证random pointer指向的节点永远都是已经建立的新节点,不会是null

/**
 * 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 {
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    public RandomListNode copyRandomList(RandomListNode head) {
        // write your code here
        if(head == null)
            return null;
        
        RandomListNode newhead = new RandomListNode(head.label);
        RandomListNode p1 = head.next;
        RandomListNode p2 = newhead;
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        map.put(head, newhead);
        
        while(p1 != null){
            p2.next = new RandomListNode(p1.label);
            p2 = p2.next;
            map.put(p1, p2);
            p1 = p1.next;
        }
        
        p1 = head;
        p2 = newhead;
        
        while(p1 != null){
            p2.random = map.get(p1.random);
            p1 = p1.next;
            p2 = p2.next;
        }
        
        return newhead;
    }
}

 

以上是关于lintcode-medium-Copy List with Random Pointer的主要内容,如果未能解决你的问题,请参考以下文章

Java list1=list2;list2=null ? list1=list2;list2.clear()?

Java list1=list2;list2=null ? list1=list2;list2.clear()?

list.addAll(list1),如果list改变,怎么让list1的值不跟着改变!

如何把两个list放到一个list中,然后在页面能获取到ID

C++ list 容器

一个list怎么添加另一个list中