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

    1. Title

    Copy List with Random Pointer

    2. Http address

    https://leetcode.com/problems/copy-list-with-random-pointer/

    3. The question

    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.

     4. My code(AC)

     1 class RandomListNode {
     2     int label;
     3     RandomListNode next,random;
     4     public RandomListNode(int x)
     5     {
     6             this.label = x;
     7     }
     8 
     9 }
    10 
    11 //Accpeted
    12     public static RandomListNode copyRandomList(RandomListNode head)
    13     {
    14             Map<RandomListNode,RandomListNode> mapH = new HashMap<RandomListNode,RandomListNode>();
    15             RandomListNode re,    q,end;
    16             RandomListNode p = head;
    17             re = null;
    18             end = null;
    19             while( p != null )
    20             {
    21                 q = new RandomListNode(p.label);
    22                 if( end == null)
    23                 {
    24                     re = q;
    25                     end = q;
    26                 }else{
    27                     end.next = q;
    28                     end = q;
    29                 }
    30                 mapH.put(p,q);
    31                 p = p.next;
    32             }
    33 
    34             p = head;
    35             q = re;
    36             while( p != null && q != null) {
    37                 if( p.random != null )
    38                 {
    39                     q.random = mapH.get(p.random);
    40                 
    41                 }else{
    42                     q.random = null;
    43                 }
    44                 p = p.next;
    45                 q = q.next;
    46             }
    47         return re;
    48 
    49     }
     
  • 相关阅读:
    MyBatis总结(一)
    MyBatis简介
    数据持久化与ORM
    主流框架介绍
    JSP数据交互(一)
    tomcat端口被占用
    动态网页开发基础
    jQuery内容
    正则表达式
    初始Mybatis
  • 原文地址:https://www.cnblogs.com/ordili/p/4970002.html
Copyright © 2011-2022 走看看