Algorithm problem: copy the linked list with random pointer

Keywords: Programming Java

Topic Description: given a linked list, each node contains an additional random pointer, which can point to any node or empty node in the linked list.
Requirement: return the deep copy of this linked list.

Idea: first, change the structure of the original list. After each node, a copy of the node is copied. After traversing the entire list for the first time, the nodes in the list are one original and one copy. However, the references of random are null except that the label s of the copied nodes are the same as the previous original nodes. The second time, we traverse the list from the beginning, only the original nodes. Every time I check whether the random in the original node is null. If it is null, the random value of the next copy node of the original node is null; otherwise, the random value of the next copy node of the original node = the random.next of the original node. Why can we quickly locate the random value of the copy node here? The credit is that we changed the structure of the list for the first time, so that the structure of the list is an original node, and then a copy. Finally, the third traversal from the beginning separates the original nodes from the copied ones.
java implementation:

/**
 * 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 {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head==null){
            return null;
        }
        RandomListNode p=head;
        while(p!=null){
            RandomListNode next=p.next;
            RandomListNode copy=new RandomListNode(p.label);
            copy.random=null;
            copy.next=p.next;
            p.next=copy;
            p=next;
        }
        p=head;
        while(p!=null){
            if(p.random==null){
                p.next.random=null;
            }
            else{
                p.next.random=p.random.next;
            }
            p=p.next.next;
        }
        RandomListNode start=head.next;
        p=start;
        RandomListNode q=head;
        while(p!=null && p.next!=null){
            q.next=p.next;
            q=q.next;
            p.next=p.next.next;
            p=p.next;
        }
        q.next=null;
        return start;
    }
}

OVER

Posted by rcatal02 on Thu, 12 Dec 2019 11:54:06 -0800