zoukankan      html  css  js  c++  java
  • LeetCode _ Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
    
    Return a deep copy of the list.
    

    剑指offer里面的一道题,具体思路看不懂请查阅剑指offer

    /**
     * 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:
        void copyFirst(RandomListNode *head){
            
            RandomListNode *pcur, *pnext, *q;
            pcur = head;
            while(pcur != NULL){
                pnext = pcur->next;
                q = new  RandomListNode(pcur->label);
                q->next = pnext;
                pcur->next = q;
                pcur = pnext;
            }
        }
        void fixRandom(RandomListNode * head){
            
            RandomListNode *ph = head;
            while(ph!=NULL){
                if(ph->random != NULL)
                    ph->next->random = ph->random->next;
                ph = ph->next->next;    
            }
        }
        RandomListNode * getCopy(RandomListNode *head){
                
            RandomListNode *p,*rcur,*q, *res;
            res = NULL; p = head;rcur = NULL;
            while(p != NULL){
                q  = p->next;
                p->next = q->next;
                p = p->next;
                if(res == NULL){
                    res = q;
                    rcur = q;
                }else{
                    rcur->next = q;
                    rcur = q;
                }
            }
           // rcur->next = NULL;
            return res;
            
        }
        RandomListNode *copyRandomList(RandomListNode *head) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(head == NULL) return NULL;
            copyFirst(head);
            fixRandom(head);
            return getCopy(head);
            
        }
    };
  • 相关阅读:
    Leetcode No.121
    Leetcode No.97 ***
    (描述需要改进) Leetcode No.71 **
    (描述需要改进)Leetcode No.68 **
    Leetcode No.72 ***
    【笔记】存储位置/修改表/字符集.【3(完结创建表)】
    redis 事件驱动模型解析
    redis 官网文档学习笔记 简单翻译
    redis 官网文档 sentinel 简单翻译 && 简单总结QA
    redis 学习笔记 总
  • 原文地址:https://www.cnblogs.com/graph/p/3352014.html
Copyright © 2011-2022 走看看