算法数据结构和算法分析

复制带随机指针的链表

2016-08-25  本文已影响505人  杰米

给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。

//哈希表
class Solution {
public:
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    RandomListNode *copyRandomList(RandomListNode *head) {
        // write your code here
        map<RandomListNode*,RandomListNode*> hash;
        
        RandomListNode *curr = head;
        RandomListNode *newHead = new RandomListNode(curr->label);
        
        RandomListNode * newCurr = newHead;
        
        hash[curr] = newHead;
        
        while(curr->next) {
            curr = curr -> next;
            RandomListNode *newNode = new RandomListNode(curr->label);
            hash[curr] =  newNode;
            newCurr->next = newNode;
            newCurr = newCurr->next;
            
        } 
        
         newCurr = newHead;
         curr = head;
        while(newCurr) {
            
            newCurr->random = hash[curr->random];
            newCurr = newCurr->next ;
            curr = curr->next;
    }
    return newHead;
    }
};
上一篇下一篇

猜你喜欢

热点阅读