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;
        }
    }
  • 相关阅读:
    latch与DFF
    数字逻辑综合DC脚本示例及解释
    当DiscuzNT遇上了Loadrunner(下)
    [C#学习]在多线程中如何调用Winform
    并发性测试工具
    当DiscuzNT遇上了Loadrunner(上)
    大型网站(高访问、海量数据)技术架构
    Load Runner下载
    Invoke 和 BeginInvoke 的真正涵义
    当DiscuzNT遇上了Loadrunner(中)
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3554241.html
Copyright © 2011-2022 走看看