Copy of complex linked list

Keywords: Java

Test point: decomposition makes complex problems simple

https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussion

Title Description

Enter a complex linked list (each node has a node value, and two pointers, one to the next node, and another special pointer random to a random node). Please make a deep copy of this linked list and return the copied head node. (Note: please do not return the node reference in the parameter in the output result, otherwise the problem determination program will directly return null)
 

Solutions to problems

 

 

Link: https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussion
Source: niuke.com

/*
*Solutions:
*1. Traverse the list and copy each node. For example, copy node a to get A1, and insert node A1 after node a;
*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;
*3. Split the linked list into the original one and the copied one
*/
 
/*
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 currentNode = pHead;
        //1,Copy each node, such as a copy node A obtain A1,The node A1 Insert to node A Back;
        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 alkhatareykha on Mon, 11 May 2020 10:53:13 -0700