1 package leetcode; 2 3 class RandomListNode { 4 int label; 5 RandomListNode next, random; 6 7 public RandomListNode(int x) { 8 this.label = x; 9 } 10 } 11 12 public class CopyListRandom { 13 public RandomListNode copyRandomList(RandomListNode head) { 14 if(head==null)return head; 15 RandomListNode po= head.next; 16 RandomListNode p=head; 17 while(p!=null){ 18 RandomListNode newnode=new RandomListNode(p.label); 19 po=p.next; 20 newnode.next=p.next; 21 p.next=newnode; 22 23 p=po; 24 } 25 p=head; 26 while(p!=null){ 27 if(p.random!=null){ 28 p.next.random=p.random.next; 29 } 30 p=p.next.next; 31 } 32 p=head; 33 RandomListNode h=head.next; 34 RandomListNode q=h; 35 while(q!=null){ 36 p.next=q.next; 37 p=q; 38 q=q.next; 39 } 40 return h; 41 } 42 }
leetcode--011 copy list with random pointer
时间: 2024-10-08 18:58:53