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

    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    Ref: http://fisherlei.blogspot.com/2013/11/leetcode-copy-list-with-random-pointer.html

    如图分三步:

    http://lh6.ggpht.com/-xlfWkNgeNhI/Uomwl3lB47I/AAAAAAAAHsQ/V8DofvkKR68/s1600-h/image%25255B8%25255D.png

    1. 插入拷贝节点

    2. 复制random指针

    3.分解至两个独立列表

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
         public RandomListNode copyRandomList(RandomListNode head) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(head == null){
                return head;
            }
            
            cloneNodes(head);
            setRandomPointer(head);
            return reconnectNodes(head);
        }
        
         public RandomListNode cloneNodes(RandomListNode head){
            RandomListNode p1 = head;
            while(p1 != null){
                RandomListNode c1 = new RandomListNode(p1.label);
                c1.next = p1.next;
                p1.next = c1;
                p1 = c1.next;
            }
            return head;
        }
        
        public RandomListNode setRandomPointer(RandomListNode head){
            RandomListNode p1 = head;
            while(p1 != null){
                RandomListNode r1 = p1.random;
                if(r1 != null){
                    p1.next.random = r1.next;
                }
                p1 = p1.next.next;
            }
            return head;
        }
        
        public RandomListNode reconnectNodes(RandomListNode head){
            RandomListNode cloneHead = head.next;
            RandomListNode p1 = head;
            RandomListNode p2 = cloneHead;
            while(p1 != null && p2 != null){
                p1.next = p2.next;
                p1 = p1.next;
                if(p1 != null){
                    p2.next = p1.next;
                }
                p2 = p2.next;
            }
            return cloneHead;
        }
    }
  • 相关阅读:
    Getting Started with Recovery Manager (RMAN) (文档 ID 360416.1)
    enctype的2个值
    laravel 去掉资源的顶层包裹 withoutWrapping方法
    hash_equals(),防止时序攻击,字符串比较函数
    moment.js 处理“几天前”,“几个月前”
    redis hash 应用场景
    vue 3个插槽示例(具名插槽)
    vue 插槽的基本使用
    redis hash
    redis 分布式系统全局序列号
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3554241.html
Copyright © 2011-2022 走看看