剑指offer:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。

本文介绍了一种复杂链表的深拷贝方法,通过三步实现:首先复制每个节点并插入原节点后,接着更新新节点的随机指针,最后拆分原链表和拷贝链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

剑指offer算法题


链表

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

题目分析
Alt

  • 解题思路:
  • 1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
  • 2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
  • 3、拆分链表,将链表拆分为原链表和复制后的链表

下面是Java代码

/*
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;
        }
        
        RandomListNode tmpHead = new RandomListNode(pHead.label);
        RandomListNode tmp = pHead;
        //1、复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
        while(tmp!=null){
            RandomListNode cloneNode = new RandomListNode(tmp.label);
            RandomListNode nextNode = tmp.next;
            tmp.next = cloneNode;
            cloneNode.next = nextNode;
            tmp = nextNode;
            
        }
        
        tmp = pHead;
         //2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
        while(tmp!=null){
            tmp.next.random = tmp.random==null? null: tmp.random.next;
            tmp = tmp.next.next;
        }
        
        tmp = pHead;
        RandomListNode pNewHead = pHead.next;
        
         //3、拆分链表,将链表拆分为原链表和复制后的链表
        while(tmp!=null){
            RandomListNode cloneNode = tmp.next;
            tmp.next = cloneNode.next;
            cloneNode.next = cloneNode.next ==null?null:cloneNode.next.next;
            tmp = tmp.next;
        }

        return pNewHead;  
    }
}

参考https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&&tqId=11178&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值