JZ25 复杂链表的复制

  • 思想,复制RandomListNode时,需要复制next,random两个的值,两个值是next.label, random.label
  • 时间:2021年8月6日
/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    private RandomListNode result = new RandomListNode(-1); //头节点;
    public RandomListNode Clone(RandomListNode pHead) {

        if (pHead == null)
            return null;

        doClone(pHead, result);

        return result.next;
    }

    public void doClone(RandomListNode pHead, RandomListNode resultNode) {
        if (pHead == null)
            return;

        resultNode.next = new RandomListNode(pHead.label);
        resultNode.next.next = pHead.next == null? null : new RandomListNode(pHead.next.label);
        resultNode.next.random = pHead.random == null? null : new RandomListNode(pHead.random.label);


        doClone(pHead.next, resultNode.next);
    }

}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务