zoukankan      html  css  js  c++  java
  • 138. 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.

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
     
     /* 
       create a hashmap store <oldNode, newNode>
       copy value and next to new list
       copy random node in hashmap for new list
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head == null) return null;
            RandomListNode newhead = new RandomListNode(head.label);
            RandomListNode newl = newhead;
            RandomListNode oldl = head.next;
            HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
            map.put(head, newhead);
            while(oldl != null){
                RandomListNode newNode = new RandomListNode(oldl.label);
                map.put(oldl, newNode);
                newl.next = newNode;
                
                oldl = oldl.next;
                newl = newl.next;
            }
            
            oldl = head;
            newl = newhead;
            while(oldl != null){
                newl.random = map.get(oldl.random);
                
                newl = newl.next;
                oldl = oldl.next;
            }
            return newhead;
        }
    }
  • 相关阅读:
    PHP小技巧
    PHP Ajax跨域解决
    单点登录
    Linux 常用命令
    php面向对象--继承
    vueDemo
    vueSource
    vuex
    Vue.js
    关于前后端分离
  • 原文地址:https://www.cnblogs.com/joannacode/p/6108706.html
Copyright © 2011-2022 走看看