138. Copy List with Random Pointer(解法好!!!)

138. Copy List with Random Pointer(解法好!!!)_第1张图片
image.png

解法一:用hash,将新旧地址对应起来

/**
 * 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 == NULL){
            return NULL;
        }
        RandomListNode * dummy = new RandomListNode(0);
        RandomListNode * p = dummy;
        RandomListNode * h = head;
        map hash;
        while(h){
            RandomListNode * tmp = new RandomListNode(h->label);
            cout<label<next = tmp;
            p = p->next;
            tmp->random = h->random;
            hash[h] = tmp;
            h = h->next;
        }
        p  = dummy->next;
        while(p){
            if(p->random != NULL){
                p->random = hash[p->random];
            }
            p = p->next;
        }
        return  dummy->next;
    }
};

解法二:
一个更好的思路:
https://siddontang.gitbooks.io/leetcode-solution/content/linked_list/copy_list_with_random_pointer.html

138. Copy List with Random Pointer(解法好!!!)_第2张图片
image.png

要注意的事情是,可以copy,但是一定不要改变原来的序列,即以head开头的序列!!!否则会报错。最后一个while中的h,一定要有一个h->next = p->next; h = h->next的过程,一个遍历的过程!!!!!

/**
 * 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) {
        RandomListNode *dummy = new RandomListNode(0);
        dummy->next = head;
        RandomListNode *h = head;
        if(head == NULL) {
            return NULL;
        }
        while(h){
            RandomListNode *post = h->next;
            RandomListNode * tmp = new RandomListNode(h->label);
            tmp->random = h->random;
            h->next = tmp;
            tmp->next = post;
            h = post;
        }
        h = head->next;
        while(h){
            if(h->random != NULL) {
                h->random = h->random->next;
            }
            if(h->next == NULL){
                break;
            }
            h = h->next->next;
        }
        RandomListNode *p = dummy, *n;
        h = head;
        while(h){
            p->next = h->next;
            if(h->next == NULL){
                break;
            }
            p = p->next;
            h->next = p->next;
            h = h->next;
           
        }
        return dummy->next;
    }
};

你可能感兴趣的:(138. Copy List with Random Pointer(解法好!!!))