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;
        }
    };
  • 相关阅读:
    HDU 1017—A Mathematical Curiosity
    N !
    L
    J
    Danganronpa
    A water problem
    hdu 5461 Largest Point
    India and China Origins hdu 5652 (BFS+二分)
    D (多校训练三) poj1919 (二分)
    Discovering Gold lightoj 1030 (dp+期望)
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4159408.html
Copyright © 2011-2022 走看看