首页 > 其他 > 详细

Copy List with Random Pointer

时间:2014-02-22 22:17:27      阅读:377      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣
 1 public class Solution {
 2     public RandomListNode copyRandomList(RandomListNode head) {
 3         //insert nodes
 4         RandomListNode cur = head;
 5         while(cur!=null){
 6             RandomListNode temp = new RandomListNode(cur.label);
 7             temp.next = cur.next;
 8             cur.next = temp;
 9             cur = temp.next;
10         }
11         //copy random pointers
12         cur = head;
13         while(cur!=null){
14             RandomListNode temp = cur.next;
15             if(cur.random!=null)
16                 temp.random = cur.random.next;
17             cur = temp.next;
18         }
19         cur = head;
20         RandomListNode newHead = head==null?null:head.next;
21         while(cur!=null){
22             RandomListNode temp = cur.next;
23             cur.next = temp.next;
24             if(temp.next!=null)
25                 temp.next = temp.next.next;
26             cur = cur.next;
27         }
28         return newHead;
29     }
30 }
View Code

Copy List with Random Pointer

原文:http://www.cnblogs.com/krunning/p/3560673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!