zoukankan      html  css  js  c++  java
  • 【酷家乐社招面试题】【148.排序链表】

    如何链表深拷贝

    思路:用1个map保存旧链表和新链表节点的映射关系。

    在复制旧链表节点node、node的next节点、node的random节点时,都去map去看下是否存在;

    存在则直接返回,构建链表指针指向关系;不存在则new 一个节点出来。

    class Solution {
    
        private Map<Node, Node> map = new HashMap<>();
    
        public Node copyRandomList(Node head) {
            if (head == null) {
                return null;
            }
    
            Node pNode = new Node(-1);
            Node copHead = pNode;
            while (head != null) {
                Node curNode = buildCurNode(head);
                pNode.next = curNode;
                pNode = pNode.next;
                head = head.next;
            }
    
            return copHead.next;
            
        }
    
        private Node buildCurNode(Node head) {
            Node curNode = getNode(head);
            curNode.next = getNode(head.next);
            curNode.random = getNode(head.random);
    
            return curNode;
        }
    
    
        private Node getNode(Node head) {
            if (head == null) {
                return null;
            }
    
            Node node = null;
            // map中存在则返回旧节点指向的新节点;否则new 一个新的节点
            if (map.containsKey(head)) {
                node = map.get(head);
            } else {
                node = new Node(head.val);
                map.put(head, node);
            }
            return node;
        }
    
    }
  • 相关阅读:
    kafka搭建
    kafaka学习笔记
    metastore 简单说明
    二 python并发编程之多进程-理论
    文件指针偏移量
    FTP
    1 并发编程
    操作系统简介
    1 网络编程
    网络编程-osi七层
  • 原文地址:https://www.cnblogs.com/noaman/p/14503284.html
Copyright © 2011-2022 走看看