Complex linked list copy

Title Description
Input a complex linked list (each node has a node value, and two pointers, one points to the next node, and the other special pointer points to any node), and the returned result is the head of the complex linked list after replication. (Note, please do not return the node reference in the parameter in the output result, otherwise the problem judgment program will directly return empty)

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead == null)
            return null;
        RandomListNode res;
        RandomListNode p = pHead;
        while(p != null){           
            RandomListNode q = new RandomListNode(p.label);
            q.next = p.next;
            p.next = q;
            p = q.next;                     
        }
        p = pHead;
        while(p != null){
            RandomListNode p2 = p.next;
            if(p.random != null)            
                p2.random = p.random.next;
            p = p2.next; 
        }

        p = pHead;
        res = p.next;
        while(p != null){
            RandomListNode p2 = p.next;
            RandomListNode tmp = p2.next;
            if(tmp == null){
                p2.next = tmp;
            }else{
                 p2.next = tmp.next;
            }                            
            p.next = tmp;
            p = tmp;
        }

        return res;        
    }
}

(1) First add a node after each node
(2) Copy the random pointer of each newly added node according to the random of the previous pointer! Note here that you must judge if(p.random != null)because p.random.next() is used later. If null is not judged here, a null pointer error will occur!
(3) When splitting the array, the last node must also be judged, because there will be a null pointer at the end to indicate the end of the linked list, and the new complex linked list has no null pointer, so it is necessary to add one reasonably! And it is used later tmp.next, the pointer of this kind of pointer is best to judge null! ! !

Reference:
https://blog.csdn.net/u012289407/article/details/46609731

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325616108&siteId=291194637