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

来源:互联网 发布:大数据工资一般多少 编辑:程序博客网 时间:2024/06/06 08:43

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
原创粉丝点击