剑指offer-复杂链表的复制

25.复杂链表的复制

题目描述

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

解题思路:若不限制额外空间,可以HashMap来存储结点,先遍历原链表的每个结点,同时对每个结点进行复制,把原结点和复制后的结点都加入HashMap中,我们可以根据原结点找到对应的复制结点,要找到复制结点的下一个结点可根据原结点的下一个结点找到。

  public RandomListNode Clone(RandomListNode pHead)
    {
        HashMap<RandomListNode,RandomListNode>  map=new HashMap<>();
        RandomListNode node=pHead;
        while(node!=null)
        {
            map.put(node,new RandomListNode(node.label));
            node=node.next;
        }
        node=pHead;
        while(node!=null)
        {
            map.get(node).next=map.get(node.next);
            map.get(node).random=map.get(node.random);
            node=node.next;
        }
        return map.get(pHead);
    }

解题思路2:若不允许用额外空间,则可以分三步循环遍历,第一步对原链表的每个结点进行复制,并将复制后的结点插入到每个原结点的后面,第二步将复制后的结点的random指针指向自己的下一个结点,第三步将复制后的链表与原链表分离开。


public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        if(pHead == null) {
            return null;
        }
         
        RandomListNode current = pHead;
        while(current != null){
            RandomListNode clone = new RandomListNode(current.label);
            RandomListNode next = current.next;
            current.next = clone;
            clone.next = next;
            current = next;
        }
         
        current = pHead;
        while(current != null) {
            current.next.random = current.random==null?null:current.random.next;
            current = current.next.next;
        }
      
        current= pHead;
        RandomListNode cloneHead = pHead.next;
        while(current!= null) {
            RandomListNode clone = current.next;
            current.next = clone.next;
            clone.next = clone.next==null?null:clone.next.next;
            current = current.next;
        }
         
        return cloneHead;
    }
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值