单链表(带random指针)深拷贝(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; } 
* }; 
*/

分析:

原来的链表的结构如下图所示:

image

注意一点,random的指针可以指向后面的结点,也可以指向前面的结点。

这里提供两种解法:

方法1:用hash表存储结点信息,时间O(2n),空间O(n)

第一次遍历原链表,并构建random为null的新链表,于此同时在hash表中存储原结点和新结点的地址信息,原结点地址为key,新结点地址为value,即map<原结点地址,新结点地址>

第二次遍历原链表,对于random不为空的结点,可以根据random的值,在hash表中找到random指向的节点对应的新结点的地址,再以此给新结点random赋值即可。

方法2:先改变原链表的结构,在恢复,时间O(2n),空间O(1)

这个方法需要3次遍历,

第一次,构建新链表的结点,random为null,并且用原来链表节点的next指向对应的新结点,新结点的next指向原链表的下一个结点,如图所示:

image

第二次,给新节点的random赋值,

p = head;
        while(p!=null){
            if(p.random != null){
                p.next.random = p.random.next;
            }
            p = p.next.next;
        }

第三次,恢复原链表和新链表的链表结构。

head2 = head.next;
        p = head;
        while(p!=null){
            p2 = p.next;
            p.next = p2.next;
            if (p2.next != null) p2.next = p2.next.next;
            p = p.next; 
        }

 方法2的完整代码:

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)return null;
        RandomListNode head2,p2,p = head;
        while(p!=null){
            RandomListNode n = new RandomListNode(p.label);
            n.next = p.next;
            p.next = n;
            p = n.next;
        }
        p = head;
        while(p!=null){
            if(p.random != null){
                p.next.random = p.random.next;
            }
            p = p.next.next;
        }
        
        head2 = head.next;
        p = head;
        while(p!=null){
            p2 = p.next;
            p.next = p2.next;
            if (p2.next != null) p2.next = p2.next.next;
            p = p.next; 
        }
        return head2;
    }
}
原文地址:https://www.cnblogs.com/linghu-java/p/9001738.html