zoukankan      html  css  js  c++  java
  • leetcode[138] Copy List with Random Pointer

    这里是复制带有一个random指针的链表。是不是很熟悉啊。之前有做过克隆无向图的。那就借助leetcode Clone Graph的思路。

    分两次遍历链表,一次先复制普通的含next的,另一次就是复制random了。利用map记录,可以一次就找到想要的点。

    /**
     * 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:
        RandomListNode *copyRandomList(RandomListNode *head)
        {
            if (!head) return head;
            RandomListNode *pre = new RandomListNode(0), *proc = head, *root = pre, *tmp_pre = pre;
            unordered_map<RandomListNode *, RandomListNode*> umap;
            while (proc)
            {
                root -> next = new RandomListNode(proc -> label);
                umap[proc] = root -> next;
                proc = proc -> next;
                root = root -> next;
            }
            while (head)
            {
                tmp_pre -> next -> random = umap[head -> random];
                head = head -> next;
                tmp_pre = tmp_pre -> next;
            }
            return pre -> next;
        }
    };
  • 相关阅读:
    SVN 图标消失
    svn 图标不显示
    wamp 局域网访问
    php程序 注册机制
    ThinkphpCMF笔记
    thinkphp缓存
    wampserver与 thinkphp 安装
    js function集合
    php function集合
    php sleep
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4159408.html
Copyright © 2011-2022 走看看