Loading

剑指Offer35.复杂链表复制

题目链接:复杂链表复制

思路:哈希表。先遍历一遍用hash表存储新旧链表对应的结点,然后再遍历一遍通过哈希表确定新链表中random所指向的结点。

代码:

/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
class Solution {
    public Node copyRandomList(Node head) {
        Map<Node, Node> randomMap = new HashMap<>();
        Node t = null;
        for(Node p = head, q=null, pre = null; p != null; p = p.next){
            q = new Node(p.val);
            if(t == null){
                t = q;
            }else{
                pre.next = q;
            }
            pre = q;
            randomMap.put(p, q);
        }
        for(Node p = head, q = t; p != null; p = p.next, q = q.next){
            q.random = randomMap.get(p.random);
        }
        return t;
    }
}
posted @ 2020-12-28 00:12  yoyuLiu  阅读(52)  评论(0编辑  收藏  举报