剑指offer之复杂链表的复制

本文介绍了一种特殊的链表复制算法,该算法能够处理带有随机指针的复杂链表结构。通过三个步骤实现:首先复制节点并插入原节点之后;接着更新新节点的随机指针;最后分离原始链表和复制链表。

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

这道题一定要注意括号里面的东西,(输出结果中请不要返回参数中的节点引用)。也就是说,

最后的返回的链表中的节点一定不能和原来链表中的某个节点指向同一个节点,即不能引用。

所以必须分三步进行处理:

1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面

 2、遍历链表,A1->random = A->random->next;
 3、将链表拆分成原链表和复制后的链表

代码如下:

/*
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(null == pHead){
            return null;
        }
        RandomListNode cur = pHead;
        while(cur!=null){
            RandomListNode temp = new RandomListNode(cur.label);
            temp.next = cur.next;
            cur.next = temp;
            cur = temp.next;            
        }
        cur = pHead;
        while(cur!=null){
            if(cur.random != null){
                 cur.next.random = cur.random.next;
            } 
            cur=cur.next.next;
        }
        RandomListNode result = pHead.next;
        RandomListNode pCur = result;
        cur = pHead;
      while(cur!= null){
          cur.next = cur.next.next;
          if(pCur.next != null){
              pCur.next= pCur.next.next;
          }
          cur=cur.next;
          pCur = pCur.next;
      }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值