剑指offer 复杂链表复制

题目描述:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

解题思路:

使用一个hashmap来存储原始链表和复制链表的对应节点,首先遍历原始链表,每个节点重新开辟一个值相同的复制链表节点放入hashmap中,再遍历hashmap为复制链表每个指针放入对应的值。

代码(java):

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.HashMap; 
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        HashMap<RandomListNode,RandomListNode> map=new HashMap<RandomListNode,RandomListNode>();
        RandomListNode head=pHead;
        while(pHead!=null){
            RandomListNode tmp=new RandomListNode(pHead.label);
            map.put(pHead,tmp);
            pHead=pHead.next;
        }
        for(RandomListNode node:map.keySet()){
            RandomListNode value=map.get(node);
            if(node.next!=null){
                value.next=map.get(node.next);
            }
            if(node.random!=null){
                value.random=map.get(node.random);
            }
            map.put(node,value);
        }
        return map.get(head);
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/88656968
今日推荐