链表:带随机指针的链表的深度复制

    给定一个链表,该链表的每个节点带有一个随机指针,指向链表中的其他元素或者为null,要求对这个链表进行深度复制。

    分析:由于随机指针指向任意元素,如何把原链表的随机指针与新链表的随机指针一一对应,是这个问题的关键。

    为了实现一一对应,需在新链表与原链表的节点之间建立相互的关系,因此,可以把新链表的节点一一的先复制到原链表的节点后,使每一个新节点都是原节点的next。复制完成之后,新节点的随机指针需要指向的目标就是原节点的随机指针的next。最后,在把两个节点分开。

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
   public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
        	return null;
        RandomListNode curr = head;
        RandomListNode result = new RandomListNode(0);
        RandomListNode tail = result;
        while(curr != null){    //复制新元素,把新元素链接到原元素的next
        	RandomListNode copy = new RandomListNode(curr.label);
        	copy.next = curr.next;
        	curr.next = copy;
        	curr = copy.next;
        }
        curr = head;
        while(curr != null){    //新元素的random指向的目标,就是原元素的random所质量的目标的next
            if(curr.random == null)
                curr.next.random = null;
            else
        	    curr.next.random = curr.random.next;
        	curr = curr.next.next;
        }
        curr = head;
        while(curr != null){    //把新元素抽取出来,得到复制的链表
        	tail.next = curr.next;
        	tail = tail.next;
        	curr.next = tail.next;
        	curr = curr.next;
        }
        return result.next;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值