zoukankan      html  css  js  c++  java
  • 链表操作 —— 138_复制带随机指针的链表

    5. 138_复制带随机指针的链表
    /*
    给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
    
    要求返回这个链表的 深拷贝。 
    
    我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
    
    val:一个表示 Node.val 的整数。
    random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。
    */
    
    class Solution {
        public Node copyRandomList(Node head) {
            if(head == null) return null;
            Node cur = head;
            Node node = null;
            while(cur != null){
                node = new Node(cur.val);
                node.next = cur.next;
                cur.next = node;
                cur = node.next;
            }
    		//复制随机节点
            cur = head;
            while(cur != null){
                if(cur.random !=null) cur.next.random = cur.random.next;
                else cur.next.random = null;
                cur = cur.next.next;
            }
    		//分解合成的链表
            Node ret = head.next;
            cur = head;
            Node tmp = ret;
            while(tmp.next != null){
                cur.next = tmp.next;
                cur = cur.next;
                tmp.next = cur.next;
                tmp = tmp.next;
            }
            //处理原链表最后一个指针
            cur.next = null;
            return ret;
        }
    }
    
  • 相关阅读:
    其他内容
    html标签
    ambari安装集群下安装kafka manager
    greenplum-cc-web4.0监控安装
    ambari安装集群下python连接hbase之安装thrift
    hadoop运维问题记录
    Ambari2.6.0 安装HDP2.6.3(离线安装)
    mongodb 定时备份
    linux top命令详解
    Sublime Text3配置Python环境
  • 原文地址:https://www.cnblogs.com/s841844054/p/13736298.html
Copyright © 2011-2022 走看看