Leetcode 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.The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:val: an integer representing Node.valrandom_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
解析
刚看到这道题目的时候理解错了,以为node.random是一个数字,主要是他这个例子的表述方法有点让人误导。然后这道题看Leetcode的官方解法一脸懵,不太懂为啥这个题目要这么麻烦,后面看到了一种不那么麻烦的解法,这边就暂时先用这种不那么麻烦的解法,等二刷再研究leetcode的官方解法吧
解法:利用hashtable
这种解法的关键思想是,由于每个node的random point可能会指向任何一个node,所以在一次顺序遍历list中很难直接将random point也做好。为了更加方便的寻找random pointer指向的节点,可以把原来的node作为key,copy后的node作为值的方式存入hashtable。具体做法如下:
- 首先第一次顺序遍历原链表,构造一个传统意义上只有next的链表,同时将原node和copy_node以键值对方式储存
- 再次遍历原链表