leetcode:Copy List with Random Pointer 细致分析,以及代码实现(JAVA版本)

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Subscribe to see which companies asked this question

题目分析:深度复制链表,既要复制next,又要复制random,next好复制,random要怎么处理呢,考虑到我们只知道链表的下一个节点是什么。那我们就在链表之后插入复制的节点,之后再进行调整。

可以分为3步:

1.在每个节点后插入复制的节点

2.复制random

3. 分离两条链表

具体代码如下:

 public RandomListNode copyRandomList(RandomListNode head) {
		 if(head==null) return null;
		 RandomListNode  newhead=null;
		 RandomListNode  now=head;
		 //  第一步在当前节点之后,插入赋值节点
		 while(now!=null)
		 {
			 RandomListNode copy=new RandomListNode(now.label);
             copy.next=now.next;
			 now.next=copy;
			 now=now.next.next;
		 }
		 
		 //第二步,拷贝RandomNode
		 now=head;
		 while(now!=null)
		 {
			 if(now.random!=null)
				 now.next.random=now.random.next;
			 now=now.next.next;
		 }
		 
		 //第三步,还原两条链表
		 now=head;
		 newhead=now.next;
		 RandomListNode p=newhead;
		 while(now!=null)
		 {
			 now.next=now.next.next;
			 //当之后没有节点时,p.next=null。需要进行非空判断
			 if(p.next!=null)
			    p.next=p.next.next;
			 now=now.next;
			 p=p.next;
		 }
		 return newhead;
	    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值