剑指offer35---复杂链表的复制

复杂链表的复制

题目描述:

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null.

题目思路:

用一个Map保存节点和这个节点的复制。

遍历链表,按照顺讯将复制节点串联。

题目代码:

public class offer35 {
    
    
    class Node {
    
    
        int val;
        Node next;
        Node random;
        public Node(int val) {
    
    
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
    //创建一个map,K为原始节点,V为K的复制节点
    Map<Node,Node> map = new HashMap<>();
    public Node copyRandomList(Node head) {
    
    
        //判断为空
        if (head == null) return null;
        // temp指向head
        Node temp = head;
        //遍历将每个节点的复制节点穿起来
        while(temp!= null){
    
    
            Node node = copyNode(temp);//获取当前节点的复制
            node.next = copyNode(temp.next);//复制节点的后驱指向原始节点的后驱的复制
            node.random = copyNode(temp.random);//复制节点的random指向原始节点的random的复制
            temp = temp.next;
        }
        return copyNode(head);
    }
    private Node copyNode(Node node) {
    
    
        if (head == null) return null;
        if (! map.containsKey(node)){
    
    
             map.put(node,new Node(node.val));
        }
        return map.get(node);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31702655/article/details/105766386
今日推荐