[LeetCode] 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.

Challenge

Could you solve it with O(1) space?

分析:这题的难点是怎么拷贝Random Pointer的关系。一种传统做法是用HashMap建立原节点和Copy节点的映射关系。然后第二遍遍历时,通过查这个表来建立新节点之间Random Pointer的关系。但是这个会超Space的limit。

参考网上大牛的做法(妈的,典型的谁背到了谁会题,哈哈哈)。巧妙的做法是在每个原节点后边插入拷贝节点。然后

就有了神奇的关系:
curr.next.random = curr.random.next;

第一遍遍历:在原节点后边插入拷贝的新节点

第二遍遍历:建立新节点之间的Random关系

第三遍遍历:去掉原节点和新节点之间的关系。

⚠️注意NPE!!

/**
 * 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 {
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
            return null;
        }
        
        RandomListNode curr = head;
        while (curr != null) {
            RandomListNode n = new RandomListNode(curr.label);
            RandomListNode next = curr.next;
            curr.next = n;
            n.next = next;
            curr = curr.next.next;
        }
        
        RandomListNode res = head.next;
        curr = head;
        while (curr != null) {
            if (curr.random != null) {
                curr.next.random = curr.random.next;
            }
            curr = curr.next.next;
        }
        
        curr = head;
        
        while (curr != null) {
            RandomListNode copy = curr.next;
            curr.next = copy.next;
            if (copy.next != null) {
                copy.next = curr.next.next;
            }
            curr = curr.next;
        }
        
        return res;
    }
}

 

 

 

posted @ 2019-05-29 06:32  英儿33  阅读(192)  评论(0)    收藏  举报