LeetCode: 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.

我想到了一个时间O(n),空间O(n)的算法。

关键要注意的地方是,头节点一定不要忘了放入hashmap中,最后一个节点的next赋值为null。

Method 1 (Uses O(n) extra space)
This method stores the next and arbitrary mappings (of original list) in an array first, then modifies the original Linked List (to create copy), creates a copy. And finally restores the original list.

1) Create all nodes in copy linked list using next pointers.
3) Store the node and its next pointer mappings of original linked list.
3) Change next pointer of all nodes in original linked list to point to the corresponding node in copy linked list.
Following diagram shows status of both Linked Lists after above 3 steps. The red arrow shows arbit pointers and black arrow shows next pointers.

ArbitLinked List2

我想的是这种方法。用一个hashmap将原来的节点与新建的一一对应起来,便于random的链接。否则就要遍历什么的比较复杂了。


 

网上又看到一种时间O(n),空间O(1)的算法。

1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N afte the Nth node
2) Now copy the arbitrary link in this fashion

     original->next->arbitrary = original->arbitrary->next;  /*TRAVERSE 
TWO NODES*/

This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy of arbitrary.
3) Now restore the original and copy linked lists in this fashion in a single loop.

     original->next = original->next->next;
     copy->next = copy->next->next;

4) Make sure that last element of original->next is NULL.

大概这么个意思。

 

posted on 2014-02-06 13:20  longhorn  阅读(160)  评论(0编辑  收藏  举报

导航