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);
            
        }
    };
  • 相关阅读:
    css3中-moz、-ms、-webkit 是什么意思
    自定义AppServer
    自定义AppSession
    分离Command
    创建简单的Telnet实例
    注册表权限设置
    centos root登录password 忘记解决的方法
    ajaxFileUpload+struts2实现多文件上传
    计算机图形学(二)输出图元_6_OpenGL曲线函数_2_中点画圆算法
    linux命令的别名alias,unalias
  • 原文地址:https://www.cnblogs.com/graph/p/3352014.html
Copyright © 2011-2022 走看看