【剑指offer】复杂链表的复制

本文介绍两种复杂链表的深拷贝方法:一种使用Map实现,另一种通过复制节点并插入原链表中,完成next和random引用的复制,最后分离链表。这两种方法都有效地解决了复杂链表的复制问题。

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

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

题解一

利用map实现

import java.util.Map;
import java.util.HashMap;
/*
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;
        }
        Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        RandomListNode newHead = new RandomListNode(pHead.label);
        RandomListNode cur = pHead;
        RandomListNode newCur = newHead;
        map.put(cur, newCur);
        while(cur != null) {
            if(cur.next != null) {
                if(!map.containsKey(cur.next))
                    map.put(cur.next, new RandomListNode(cur.next.label));
                newCur.next = map.get(cur.next);
            }
            if(cur.random != null) {
                if(!map.containsKey(cur.random)) {
                    map.put(cur.random, new RandomListNode(cur.random.label));
                }
                newCur.random = map.get(cur.random);
            }
            cur = cur.next;
            newCur = newCur.next;
        }
        return newHead;
    }
}

题解二

首先复制每个结点,并插入到原链表当中,完成next引用的复制;

其次遍历链表完成random引用的复制;

最后分离链表;

/*
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 cur = pHead;
        while(cur != null) {
            RandomListNode temp = new RandomListNode(cur.label);
            temp.next = cur.next;
            cur.next = temp;
            cur = cur.next.next;
        }
        cur = pHead;
        while(cur != null) {
            if(cur.random == null)
                cur.next.random = null;
            else
                cur.next.random = cur.random.next;
            cur = cur.next.next;
        }
        cur = pHead;
        RandomListNode newHead = pHead.next;
        RandomListNode newCur = newHead;
        while(cur != null) {
            cur.next = newCur.next;
            cur = cur.next;
            if(newCur.next != null)
                newCur.next = newCur.next.next;
            newCur = newCur.next;
        }
        return newHead;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值