码迷,mamicode.com
首页 > 其他好文 > 详细

Copy List with Random Pointer

时间:2016-07-03 08:11:34      阅读:175      评论: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.

Return a deep copy of the list.

分析:

这题的关键其实是如何copy random pointer,找到一个random pointer指向的node, time complexity is O(n). 所以总的复杂度在O(n^2).

这里有一个比较巧妙的方法。在每个Node后面添加一个Node,新node的值和前一个Node一样。这样的话random pointer就很容易copy了,

技术分享

 1 /**
 2  * Definition for singly-linked list with a random pointer.
 3  * class RandomListNode {
 4  *     int label;
 5  *     RandomListNode next, random;
 6  *     RandomListNode(int x) { this.label = x; }
 7  * };
 8  */
 9 public class Solution {
10     /**
11      * @param head: The head of linked list with a random pointer.
12      * @return: A new head of a deep copy of the list.
13      */
14     public RandomListNode copyRandomList(RandomListNode listHead) {
15         if (listHead == null) return listHead;
16         RandomListNode current = listHead;
17         // add duplicate nodes
18         while(current != null) {
19             RandomListNode node = new RandomListNode(current.label);
20             node.next = current.next;
21             current.next = node;
22             current = current.next.next;
23         }
24         
25         // set random pointer
26         current = listHead;
27         while (current != null) {
28             if (current.random != null) {
29                 current.next.random = current.random.next;
30             }
31             current = current.next.next;
32         }
33         
34         // restore and detach
35         RandomListNode newHead = listHead.next;
36         RandomListNode current1 = listHead;
37         RandomListNode current2 = newHead;
38         while (current1 != null) {
39             current1.next = current2.next;
40             current1 = current1.next;
41             if (current1 != null) {  // very important, cannot remove it.
42                 current2.next = current1.next;
43             }
44             current2 = current2.next;
45         }
46         return newHead;
47     }
48 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Copy List with Random Pointer

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5636515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!