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.

HashMap法

思路

创建一个HashMap, key为原节点, value为复制的节点. 然后遍历一遍原链表, 把random指针负值给新的链表

复杂度

时间O(n) 空间O(n)

代码

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
            return head;
        }
        RandomListNode newHead = new RandomListNode(head.label);
        Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        map.put(head, newHead);
        RandomListNode node = head.next;
        RandomListNode pre = newHead;
        while (node != null) {
            RandomListNode tmp = new RandomListNode(node.label);
            map.put(node, tmp);
            pre.next = tmp;
            node = node.next;
            pre = pre.next;
        }
        node = head;
        pre = newHead;
        while (node != null) {
            pre.random = map.get(node.random);
            node = node.next;
            pre = pre.next;
        }
        return newHead;
    }
}

复制链表法

思路

深度拷贝一个链表

第一步:复制链表并插入原链表原链表(1->2->3->4)新链表(1->1'->2->2'->3->3'->4->4')
第二步: 改变新链表的random指针
第三步:分离连个链表
注意这里要判定边界条件

复杂度

时间O(n) 遍历三遍链表 空间O(1)

代码

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
            return head;
        }
        RandomListNode node = head;
        while (node != null) {
            RandomListNode tmp = new RandomListNode(node.label);
            tmp.next = node.next;
            node.next = tmp;
            node = node.next.next;
        }
        node = head;
        while (node != null) {
            if (node.random != null) {
                node.next.random = node.random.next;
            }
            node = node.next.next;
        }
        RandomListNode newHead = head.next;
        node = head;
        while (node != null) {
            RandomListNode tmp = node.next;
            node.next = tmp.next;
            if (tmp.next != null) {
                tmp.next = tmp.next.next;
            }
            node = node.next;
        }
        return newHead;
    }
}

lpy1990
26 声望10 粉丝