• LintCode-105.复制带随机指针的链表


    复制带随机指针的链表

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

    挑战

    可否使用O(1)的空间

    标签

    哈希表 链表 优步

    code

    /**
     * Definition for singly-linked list with a random pointer.
     * struct RandomListNode {
     *     int label;
     *     RandomListNode *next, *random;
     *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     * };
     */
    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
            RandomListNode * newHead;
            map<RandomListNode *, RandomListNode *> mapRandom;
    
            newHead = createListNext(head, mapRandom);
            newHead = createListRandom(head, newHead, mapRandom);
    
            return newHead;
        }
    
        RandomListNode *createListNext(RandomListNode *head, map<RandomListNode *, RandomListNode *> &mapRandom) {
            // write your code here
            RandomListNode * newHead;
            RandomListNode * p=head, *q;
    
            if(head == NULL)
                return NULL;
    
            q = newHead = new RandomListNode(p->label);
            mapRandom.insert(pair<RandomListNode *, RandomListNode *>(p, q));
            p = p->next;
    
            while(p != NULL) {
                q->next = new RandomListNode(p->label);
                mapRandom.insert(pair<RandomListNode *, RandomListNode *>(p, q->next));
                q = q->next;
                p = p->next;
            }
    
            return newHead;
        }
        RandomListNode *createListRandom(RandomListNode *head,RandomListNode *newHead, map<RandomListNode *, RandomListNode *> &mapRandom) {
            // write your code here
            RandomListNode * p=head;
            RandomListNode * q=newHead;
            
            if(head == NULL)
                return NULL;
    
            while(p != NULL) {
                if(p->random != NULL) {
                    map<RandomListNode *, RandomListNode *>::iterator it = mapRandom.find(p->random); 
                    q->random = it->second;
                }
                p = p->next;
                q = q->next;
            }
    
            return newHead;
        }
    };
  • 相关阅读:
    开学测试感想
    动手动脑1(00JAVA语言基础)
    9.29 java web注释方式以及servlet映射
    三十道随机算法
    9.30 servlet学习
    C#验证控件的使用方法
    SqlHelper详解
    C#字符串的几种常用方法
    存储过程事务处理
    js url编码
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6807479.html
Copyright © 2020-2023  润新知