Prove safety offer: replication complex list (leetcode 138)

topic:

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)

answer:

Solution one:

Read other people's ideas to write, ideas are as follows :( sources see the watermark)

illustrate

code show as below:

/*
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;
        }
        //next
        RandomListNode current = pHead;
        while(current!=null){
            RandomListNode node = new RandomListNode(current.label);
            node.next = current.next;
            current.next = node;
            current = node.next;
        }
        //random
        current = pHead;
        while(current!=null){
            current.next.random = (current.random==null?null:current.random.next);
            current = current.next.next;
        }
        //result
        current = pHead;
        RandomListNode result = pHead.next;
        while(current!=null){
            RandomListNode cloneNode = current.next;
            current.next = cloneNode.next;
            cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
            current = current.next;
        }
        
        return result;
    }
}

 Solution two:

https://leetcode-cn.com/problems/copy-list-with-random-pointer/solution/fu-zhi-dai-sui-ji-zhi-zhen-de-lian-biao-by-leetcod/

 

Published 92 original articles · won praise 2 · Views 8400

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104901630