zoukankan      html  css  js  c++  java
  • [leetcode]Copy List with Random Pointer

    这道题目以前见过,所以想了一下就想出来了http://www.cnblogs.com/lautsie/p/3259724.html。就是先修改指针维护一个从原先节点到新建节点的关系,最后再改回去。

    实现过程中,一度忘记把node往前更新了。

    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if (head == null) return null;
            RandomListNode node = head;
            // copy node and change the structure
            while (node != null) {
                RandomListNode copyNode = new RandomListNode(node.label);
                copyNode.next = node.next;
                node.next = copyNode;
                node = copyNode.next;
            }        
            node = head;
            while (node != null) {
                node.next.random = node.random == null ? null : node.random.next;
                node = node.next.next;
            }
            // re-build the structure
            node = head;
            RandomListNode copyHead = head.next;
            while (node != null) {
                RandomListNode copyNode = node.next;
                node.next = copyNode.next;
                copyNode.next = node.next == null ? null : node.next.next;
                node = node.next;
            }
            return copyHead;
        }
    }
    

      

  • 相关阅读:
    Ceph相关
    Redis学习
    docker mysql
    WebSocket学习与使用
    nginx学习与使用
    python学习小记
    基数计数——HyperLogLog
    Swagger使用小记
    理解Java枚举类型
    Jenkins使用
  • 原文地址:https://www.cnblogs.com/lautsie/p/3359636.html
Copyright © 2011-2022 走看看