138. Copy List with Random Pointer

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.

 

本题主要分为三个步骤,第一个步骤是在每个节点后面复制一个与当前节点一模一样的节点,第二步是把random的值赋值给复制的节点的random,第三步把原链表还原,并把新的链表提取出来;

代码并没有难得,就是要注意一些细节,比如random pointer which could point to any node in the list or null,random为空的情况。还有如何理解deep copy和shadow 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     public RandomListNode copyRandomList(RandomListNode head) {
11         RandomListNode iter = head,next;
12         while(iter!=null){
13             next = iter.next;
14             RandomListNode copy = new RandomListNode(iter.label);
15             iter.next = copy;
16             copy.next = next;
17             iter = next;
18         }
19         iter = head;
20         while(iter!=null){
21             if(iter.random!=null){
22                 iter.next.random = iter.random.next;
23             }
24             iter = iter.next.next;
25         }
26         iter = head;
27         RandomListNode dummy = new RandomListNode(0);
28         RandomListNode itercopy = dummy,copy;
29         while(iter!=null){
30             next = iter.next.next;
31             copy = iter.next;
32             itercopy.next = copy;
33             itercopy = itercopy.next;
34             iter.next = next;
35             iter = next;
36         }
37         return dummy.next;
38     }
39 }

 

posted @ 2017-03-15 07:37  CodesKiller  阅读(149)  评论(0编辑  收藏  举报