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.
这道题是deep copy链表,题目难度为Hard。
第一次看完题目有点不知所云,查了下deep copy的意思才明白题目要求,不知道如何翻译deep copy,就写英文了。题目的难点在于复制链表时random指针的赋值。由于原链表的random指针随机指向链表中节点或NULL,所以新链表节点在给random指针赋值之前先要生成所有节点,之后按原链表的指向顺序给random指针赋值相应位置的节点。为了记下原链表中的节点位置,很容易想到用Hash Table,根据原链表中节点random指针指向的位置,将新链表中节点random指针赋值相应的值,这样就完成了链表的deep copy。代码中没有释放内存,具体项目中大家肯定都会注意到。具体代码:
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head) return NULL;
RandomListNode *orgNode = head, *newNode = NULL;
unordered_map<RandomListNode*, int> hash;
vector<RandomListNode*> newList;
int cnt = 0;
while(orgNode) {
RandomListNode* n = new RandomListNode(orgNode->label);
newList.push_back(n);
hash[orgNode] = cnt++;
orgNode = orgNode->next;
}
orgNode = head;
for(int i=0; i<cnt; ++i) {
if(i != cnt - 1) newList[i]->next = newList[i+1];
if(orgNode->random) newList[i]->random = newList[hash[orgNode->random]];
orgNode = orgNode->next;
}
return newList[0];
}
};