• leetcode-剑指35-OK


    // language C with STL(C++)
    // 剑指35
    // https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/comments/
    // 同主站138
    // https://leetcode-cn.com/problems/copy-list-with-random-pointer/
    
    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* next;
        Node* random;
        
        Node(int _val) {
            val = _val;
            next = NULL;
            random = NULL;
        }
    };
    */
    class Solution {
    	Node* CreatANode(int val){
    		Node* ans =(Node *) malloc(sizeof(Node));
    		ans->val = val;
    		ans->next = NULL;
    		ans->random = NULL;
    		return ans;
    	}
    public:
        Node* copyRandomList(Node* head) {
        	if(head == NULL)
        		return NULL;
            // 先把链表的指针都装进一个vector里
            vector<Node*> old;
            Node* p = head;
            while(p){
            	old.push_back(p);
            	p = p -> next;
            }
            int size_old = old.size();
    
    
            int random[size_old];
            for(int i = 0 ; i < size_old; i++){
            	p = old[i]->random;
            	if(p == NULL)
            		random[i] = -1;
            	else{
            		for(int j = 0; j<size_old; j++){
            			if(p == old[j])
            				random[i] = j;
            		}
            	}
            }
    
    
    
            Node* ans[size_old];
            ans[size_old-1] = CreatANode(old[size_old-1]->val);
            ans[size_old-1] ->next = NULL;
            for(int i = size_old-2; i>=0; i--){
            	ans[i] = CreatANode(old[i]->val);
            	ans[i]->next = ans[i+1];
            }
            for(int i =0; i<size_old; i++){
            	if(random[i] != -1)
            		ans[i]->random = ans[random[i]];
            }
    
            return ans[0];
        }
    };
    
  • 相关阅读:
    eclipse workspace
    logcat and monkey
    git command
    Take Total Control of Internet Explorer with Advanced Hosting Interfaces
    #import 指令
    今天聊发兴致,写了一个 COM STEP BY STEP,结果。。。
    DECLARE_CLASSFACTORY_SINGLETON 宏
    对象微操
    宏定义缺失的解决
    读取地址本内容
  • 原文地址:https://www.cnblogs.com/gallien/p/14367759.html
Copyright © 2020-2023  润新知