Offer to prove safety of the programming problem (Java implementation) - the list of replication complex

Title Description

A complex input list (each node has a node value, and two pointers, one pointing to the next node, a special pointer to any other node), returns a value after the head of the list replication complex. (Note that the output results do not return parameter node reference, otherwise the program will return empty sentenced questions directly)

Thinking

The first step, the copied node is inserted at the back of each node.

The second step, copy the link of the random assignment of nodes.

The third step, split.

achieve

/*
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 tmpHead = pHead;
        
        // 先克隆所有的节点并插入到该节点之后
        while(tmpHead != null){
            RandomListNode insert = new RandomListNode(tmpHead.label);
            insert.next = tmpHead.next;
            tmpHead.next = insert;
            tmpHead = insert.next;
        }
        tmpHead = pHead;
        // 克隆所有节点的random节点
        while(tmpHead != null){
            if(tmpHead.random != null){
                tmpHead.next.random = tmpHead.random.next;
            }
            tmpHead = tmpHead.next.next;
        }
        tmpHead = pHead;
        RandomListNode clone = pHead.next;
        //RandomListNode tmpClone = clone;
        // 重新调整所有节点的next节点
        while(tmpHead.next != null){
            RandomListNode tmp = tmpHead.next;
            tmpHead.next = tmp.next;
            tmpHead = tmp;
        }
        return clone;
    }
}

 思路参考:https://www.nowcoder.com/discuss/198840

Guess you like

Origin www.cnblogs.com/MWCloud/p/11323096.html