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:无

  • 相关阅读:
    input上传限定文件类型
    扫描二维码自动识别手机系统(Android/IOS)
    css/html/Javascript
    移动端容易碰到的点击穿透的坑
    洛谷P3387 【模板】缩点
    洛谷P1137 旅行计划
    洛谷P2324 [SCOI2005]骑士精神
    洛谷P2571 [SCOI2010]传送带
    BZOJ4300: 绝世好题
    [洛谷P1966] 火柴排队
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7684461.html
Copyright © 2011-2022 走看看