剑指offer(25)复制含有随机指针节点的链表

class RandomListNode{
    int lebal;
    RandomListNode next;
    RandomListNode random;
    public RandomListNode(int lebal){
        this.lebal = lebal;
    }
}

public class NoTwentyfive {
    public static RandomListNode clone(RandomListNode pHead){
        if(pHead == null){
            return null;
        }
        
        RandomListNode cur = pHead;
        
        while(cur != null){
            RandomListNode next = cur.next;
            cur.next = new RandomListNode(cur.lebal);
            cur.next.next = next;
            cur = next;
        }
        
        cur = pHead;
        while(cur != null){
            RandomListNode pCloneHead = cur.next;
            RandomListNode next = cur.next.next;
            pCloneHead.random = cur.random == null ? null :cur.random.next;
            cur = next;
        }
        
        RandomListNode res = pHead.next;
        cur = pHead;
        while(cur != null){
            RandomListNode next = cur.next.next;
            RandomListNode pCloneHead = cur.next;
            cur.next = next;
            pCloneHead.next = next == null ? null : next.next;
            cur = next;
        }
        return res;
    }
    

猜你喜欢

转载自blog.csdn.net/qq_34403001/article/details/88941962