剑指offer 35. 复杂链表的复制

剑指offer 35. 复杂链表的复制

题目描述

在这里插入图片描述
在这里插入图片描述

解题思路

DFS

把复杂链表看成一个图。
在这里插入图片描述

class Solution {
    
    
	//如果原来的图已访问过某一节点,则需要返回已新建的链表头结点,所以用 HashMap 而不是 HashSet
    HashMap<Node, Node> visited = new HashMap<>();

    public Node copyRandomList(Node head) {
    
    
        if (head == null) return null;
        return dfs(head);
    }

    //定义:复制以head为起点的复杂链表,返回新链表的头结点
    public Node dfs(Node head) {
    
    
        //base case
        if (head == null) return null;
        //注意,如果已访问过,则直接返回已新建的链表,而不是返回 null 
        if (visited.containsKey(head)) return visited.get(head);

        Node copy = new Node(head.val);
        visited.put(head, copy);   //标记已访问

        copy.next = dfs(head.next);
        copy.random = dfs(head.random);
        return copy;
    }
}

HashMap 迭代

class Solution {
    
    
    public Node copyRandomList(Node head) {
    
    
        if (head == null) return null;
        //原节点 -> 新节点 的映射
        HashMap<Node, Node> map = new HashMap<>();
        Node curr = head;
        //建立 原节点 -> 新节点 的映射
        while (curr != null) {
    
    
            map.put(curr, new Node(curr.val));
            curr = curr.next;
        }
        curr = head;
        //建立新链表每个节点的指向
        while (curr != null) {
    
    
            map.get(curr).next = map.get(curr.next);
            map.get(curr).random = map.get(curr.random);
            curr = curr.next;
        }
        return map.get(head);
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115180377
今日推荐