zoukankan      html  css  js  c++  java
  • leetcode--138. Copy List with Random Pointer

    1,问题描述

    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.

    数据结构:

    1 /**
    2  * Definition for singly-linked list with a random pointer.
    3  * class RandomListNode {
    4  *     int label;
    5  *     RandomListNode next, random;
    6  *     RandomListNode(int x) { this.label = x; }
    7  * };
    8  */

    2,边界条件:root==null情况可以处理,所以没有边界条件,不需要特殊处理

    3,解题思路:先不管random指针,把链表节点依次复制,不过不是生成一个新的链表,而是把新节点放在原节点的next。然后再根据random指针把新节点的random指针指向原节点的next,即新节点。最后把大链表分离,恢复旧链表,把新节点生成一个新链表,即为旧链表的deep copy。

    4,代码实现

     1 public RandomListNode copyRandomList(RandomListNode head) {
     2     if (head == null) {
     3         return null;
     4     }
     5     RandomListNode cur = head;
     6     while (cur != null) {
     7         RandomListNode node = new RandomListNode(cur.label);
     8         node.next = cur.next;
     9         cur.next = node;
    10         cur = node.next;
    11     }
    12 
    13     cur = head;
    14     while (cur != null && cur.next != null) {
    15         if (cur.random != null) {
    16             cur.next.random = cur.random.next;
    17         }
    18         cur = cur.next.next;
    19     }
    20 
    21     RandomListNode dummy = new RandomListNode(-1);
    22     // RandomListNode copyCur = head.next;//这种写法在leetcode不通过,在lintcode上面能通过
    23     // dummy.next = copyCur;
    24     // cur = head.next.next;
    25     RandomListNode copyCur = dummy;//这里是注意下,比上面写法简洁,可以处理head=null的情况
    26     cur = head;
    27     while (cur != null && cur.next != null) {
    28         copyCur.next = cur.next;
    29         cur.next = cur.next.next;
    30         cur = cur.next;
    31         copyCur = copyCur.next;
    32     }
    33     return dummy.next;
    34 }

    5,时间复杂度:O(n),空间复杂度:O(1)

    6,api:无

  • 相关阅读:
    一个.java源文件中可以有多个类吗?(内部类除外)有什么条件?
    接口中定义的变量为什么是常量
    关于String s = new String("xyz");创建了几个字符串对象?的问题
    java面试题之----JVM架构和GC垃圾回收机制详解
    Object中的clone方法
    C/S与B/S架构的区别和优缺点
    EJB是什么?
    JNDI是什么,怎么理解
    java中什么是上下文(servletContext)
    java面试题----String、StringBuffer、StringBudder区别
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7684461.html
Copyright © 2011-2022 走看看