JZ25 复杂链表的复制

  1. 复制每个节点,如:复制节点A得到A1,将A1插入到节点A后面;
  2. 遍历链表,A1.random = A.random.next;
  3. 将链表拆分成原链表和复制后的链表。
/*
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 pHead;
        }
        RandomListNode currNode = pHead;
        while(currNode != null) {
            RandomListNode cloneNode = new RandomListNode(currNode.label);
            cloneNode.next = currNode.next;
            currNode.next = cloneNode;
            currNode = cloneNode.next;
        }
        currNode = pHead;
        while(currNode != null) {
            if(currNode.random != null){
                currNode.next.random = currNode.random.next;
            }
            currNode = currNode.next.next;
        }
        currNode = pHead;
        RandomListNode pCloneHead = pHead.next;
        //注意这里的判断条件,当走到最后一个node的时候退出循环
        //因为对于最后一个node有:currNode.next == null,所以无需对其进行操作
        //而且如果进入循环后currNode.next = nextNode.next会出错
        while(currNode.next != null) {
            RandomListNode nextNode = currNode.next;
            currNode.next = nextNode.next;
            currNode = nextNode;
        }
        return pCloneHead;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值