复制包含任意指针的链表 Copy List with Random Pointer

问题:node

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.dom

Return a deep copy of the list.this

解决:spa

【题意】深拷贝一个链表,链表除了含有next指针外,还包含一个random指针,该指针指向字符串中的某个节点或者为空。指针

① 难点就在于如何处理随机指针的问题,用Hash map来缩短查找时间,HashMap的key存原始pointer,value存新的pointer。第一遍遍历生成全部新节点时同时创建一个原节点和新节点的哈希表,第二遍给随机指针赋值时,查找时间是常数级。时间复杂度O(n),空间复杂度O(n)。字符串

假设原始链表以下,细线表示next指针,粗线表示random指针,没有画出的指针均指向NULL:get

/**
 * 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 {//4ms
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
            return null;
        }
        Map<RandomListNode,RandomListNode> map = new HashMap<>();
        RandomListNode res = new RandomListNode(head.label);//复制节点
        RandomListNode node = res;
        RandomListNode cur = head.next;
        map.put(head,res);//key为旧节点,value为新节点
        while(cur != null){ //依次建立新的节点并将它们链接起来
            RandomListNode tmp = new RandomListNode(cur.label);
            node.next = tmp;
            map.put(cur,tmp);
            node = node.next;
            cur = cur.next;
        }
        node = res;
        cur = head;
        while(node != null){
            node.random = map.get(cur.random);//由于第一遍已经把链表复制好了而且也存在HashMap里了,因此只需从HashMap中,把当前旧的cur.random做为key值,获得新的value的值,并把其赋给新node.random就好。
            node = node.next;
            cur = cur.next;
        }
        return res;
    }
}it

② 使用另外一种方法,能够分为如下三个步骤:io

1. 在原链表的每一个节点后面拷贝出一个新的节点class

2. 依次给新的节点的随机指针赋值,并且这个赋值很是容易 cur->next->random = cur->random->next

3. 断开链表可获得深度拷贝后的新链表

public class Solution {//2ms     public RandomListNode copyRandomList(RandomListNode head) {         if (head == null) {             return null;         }         RandomListNode cur = head;         while(cur != null){             RandomListNode node = new RandomListNode(cur.label);//复制节点             node.next = cur.next;             cur.next = node;             cur = node.next;         }         cur = head;         while(cur != null){//为节点赋random值             if(cur.random != null){                 cur.next.random = cur.random.next;             }             cur = cur.next.next;         }         cur = head;         RandomListNode res = head.next;         while(cur != null){//断开链接,获得复制的链表             RandomListNode tmp = cur.next;             cur.next = tmp.next;             if (tmp.next != null) {                 tmp.next = tmp.next.next;                 }             cur = cur.next;         }         return res;     } }

相关文章
相关标签/搜索