剑指Offer:复杂链表的复制(Java版)

题目:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

对于这道题,分三个步骤去考虑,① 遍历链表,将每个结点进行复制,并插入到该结点的后面

② 再次遍历链表,将每个原始结点的随机指针赋值给新结点

③ 将链表拆分为原始链表和新结点的链表

代码如下:

    public class RandomListNode {
        int label;
        RandomListNode next = null;
        RandomListNode random = null;

        RandomListNode(int label) {
            this.label = label;
        }
    }    
    public RandomListNode Clone(RandomListNode pHead) {
        if (pHead == null) {
            return null;
        }
        // 遍历链表,复制每个结点,每个复制的结点插入到被复制结点的后面
        RandomListNode currentNode = pHead;
        while (currentNode != null) {
            RandomListNode copyNode = new RandomListNode(currentNode.label);
            RandomListNode nextNode = currentNode.next;
            currentNode.next = copyNode;
            copyNode.next = nextNode;
            currentNode = nextNode;
        }
        // 再次遍历链表,将老结点的随机指针复制给copyNode
        currentNode = pHead;
        while (currentNode != null) {
            if (currentNode.random == null) {
                currentNode.next.random = null;
            } else {
                //这里之所以是currentNode.random.next,是因为如果写currentNode.random的话,这还是原始链表的结点
                //由于第一步已经将链表中所有结点都复制了一遍,并且新结点是插入在老结点后面的,所以currentNode.random
                // 实际和currentNode.random.next是相同的,只是currentNode.random.next是新复制的结点而已
                currentNode.next.random = currentNode.random.next;
            }
            currentNode = currentNode.next.next;
        }
        // 拆分链表,把链表分为原链表和复制后的链表
        currentNode = pHead;
        RandomListNode newHead = pHead.next;
        while (currentNode != null) {
            RandomListNode copyNode = currentNode.next;
            currentNode.next = copyNode.next;
            if (copyNode.next == null) {
                copyNode.next = null;
            } else {
                copyNode.next = copyNode.next.next;
            }
            currentNode = currentNode.next;
        }
        return newHead;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值