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.

Have you met this question in a real interview? Yes
Example

分析

用一个map去把copy出来的节点存储起来肯定可以。现在我们来介绍另外一种方法。
我们把原来的链表double一下,每一个节点后边跟的是它的复制出来的节点。
然后再把random变量赋值,copy出来的就是原来的random的下一个,因为copy出来的都是紧跟原来的节点。
最后再把所有的copy出来的节点形成新的链表返回就可以了。

代码

/**
 * 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) {
        // write your code here
        if (head == null) {
            return null;
        }
        RandomListNode node = head;
        while (node != null) {
            RandomListNode node1 = new RandomListNode(node.label);
            RandomListNode next = node.next;
            node.next = node1;
            node1.next = next;
            node = node.next.next;
        }
        node = head;
        while (node != null) {
            RandomListNode copy = node.next;
            if (node.random != null) {
                copy.random = node.random.next;
            }
            node = node.next.next;
        }
        RandomListNode newHead = node = head.next;
        while (node.next != null) {
            node.next = node.next.next;
            node = node.next;
        }
        return newHead;
    }
}

你可能感兴趣的:(Copy List with Random Pointer(复制带随机指针的链表))