Copy of the complex linked list

1. Title Description

Enter a complex linked list (each node has node values, and two pointers, one to the next node, and the other special pointer to any node), and the return result is the head of the copied complex linked list. (Note: please do not return the node reference in the parameter in the output result, otherwise the problem determination program will directly return null)

2. Solutions

	I didn't understand the problem. Code from others

3. code

/*
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 head = new RandomListNode(pHead.label);
        RandomListNode ans = head;
        if (pHead.random != null) {
            head.random = new RandomListNode(pHead.random.label);
        }
        while (pHead.next != null) {
            pHead = pHead.next;
            head.next = new RandomListNode(pHead.label);
            if (pHead.random != null) {
                head.next.random = new 
                                RandomListNode(pHead.random.label);

            }
            head = head.next;
        }
        return ans;
    }
}
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        if(pHead == null) {
            return null;
        }

        RandomListNode currentNode = pHead;
        //1. Copy each node. For example, copy node a to get A1, and insert node A1 after node a;
        while(currentNode != null){ 
            RandomListNode cloneNode = new RandomListNode(currentNode.label);
            RandomListNode nextNode = currentNode.next;
            currentNode.next = cloneNode;
            cloneNode.next = nextNode;
            currentNode = nextNode;
        }

        currentNode = pHead;
        //2. Traverse the linked list again, copy the random pointer of the old node to the new node, such as A1.random = A.random.next;
        while(currentNode != null) {
            currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
            currentNode = currentNode.next.next;
        }
        //3. Split the linked list into the original one and the copied one
        currentNode = pHead;
        RandomListNode pCloneHead = pHead.next;
        while(currentNode != null) {
            RandomListNode cloneNode = currentNode.next;
            currentNode.next = cloneNode.next;
            cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
            currentNode = currentNode.next;
        }

        return pCloneHead;
    }
}

Posted by tim on Fri, 01 Nov 2019 06:52:38 -0700