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.
/** * 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) { //剑指offer26题,p147 if(head==null) return null; RandomListNode cur=head; while(cur!=null){//第一步,复制node节点N',放在原始节点N的后面 RandomListNode newNode=new RandomListNode(cur.label); newNode.next=cur.next; cur.next=newNode; cur=newNode.next; } cur=head; while(cur!=null){//第二步,复制random指针 if(cur.random!=null){ cur.next.random=cur.random.next; } cur=cur.next.next; } cur=head;//第三步,把长链表拆分成两个链表,注意尾节点的处理方式 RandomListNode res=head.next; RandomListNode pnode=res; while(cur!=null){ cur.next=cur.next.next; cur=cur.next; if(pnode.next!=null)////尾节点 pnode.next=pnode.next.next; pnode=pnode.next; } return res; } }