复杂链表的复制

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

思路1:哈希
产生O(n)的空间,时间也是)(n),以空间换时间.

import java.util.HashMap;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead==null)return pHead;
        RandomListNode head=new RandomListNode(pHead.label);
        if(pHead.next==null){
            head.random=(pHead.random==null?null:head);
            return head;
        }
        HashMap<RandomListNode,RandomListNode> hm=new HashMap<>();
        hm.put(pHead,head);
        RandomListNode t_pHead=pHead,t_head=head;
        while(t_pHead.next!=null){
            RandomListNode next=new RandomListNode(t_pHead.next.label);
            t_head.next=next;
            t_pHead=t_pHead.next;
            t_head=t_head.next;
            hm.put(t_pHead,t_head);
        }
        t_pHead=pHead;
        t_head=head;
        while(t_pHead!=null){
            t_head.random=(t_pHead.random==null?null:hm.get(t_pHead.random));
            t_pHead=t_pHead.next;
            t_head=t_head.next;
        }
        return head;
    }
}

思路2:
不使用哈希表来保存对应关系,而只用有限的几个变量完成所有的功能.
1、复制链表
2、新旧链表分叉连接(旧1->新1->旧1->新1->…)
3、新链表的random,是旧链表对应结点的random的下一结点
4、断开链表得新、旧两个链表

public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead==null)return pHead;
        RandomListNode t_pHead=pHead;
        //复制结点,同时将其串接进旧链表
        while(t_pHead!=null){
            RandomListNode now=new RandomListNode(t_pHead.label);
            now.next=t_pHead.next;
            t_pHead.next=now;
            t_pHead=t_pHead.next.next;
        }
        t_pHead=pHead;
        //根据旧链表的random结点,获知新链表的random结点
        while(t_pHead!=null){
            t_pHead.next.random=(t_pHead.random==null?null:t_pHead.random.next);//注意点
            t_pHead=t_pHead.next.next;
        }
        RandomListNode head=pHead.next,t_head=head;
        t_pHead=pHead;
         //断开链表得新、旧链表
        while(t_pHead.next.next!=null){  //注意点
            t_pHead.next=t_head.next;
            t_pHead=t_pHead.next;
            t_head.next=t_pHead.next;
            t_head=t_head.next;
        }
        t_pHead.next=null;
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值