Leetcode Copy List with Random Pointer

OpenSoucre發表於2014-07-08

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.

隨機連結串列的節點資料結構

struct RandomListNode {
    int label;
    RandomListNode *next, *random;
    RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};

注意本題是對帶有隨機連結串列指標的深度拷貝,

如果資料結構中那個沒有隨機指標,只需要將連結串列遍歷拷貝一遍即可

但題目給的資料結構含有指標,拷貝後就必須保有隨機指標的關係

本題通過在每個節點之後插入一個當前節點的拷貝節點,然後讓插入的節點保有當前節點隨機指標的關係,最後將插入的節點從連結串列中剝離出來即可

主要分為3步

(1)插入拷貝的節點

(2)複製random指標

(3)將插入的節點分離出來

/**
 * 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) {
        //copy list
        RandomListNode *p = head;
        while(p){
            RandomListNode *tmp = new RandomListNode(p->label);
            tmp->next = p->next;
            p->next = tmp;
            p = tmp->next;
        }
        //copy random pointer
        RandomListNode *q = head;
        while(q){
            RandomListNode *tmp = q->next;
            if(q->random){
                tmp->random = q->random->next;
            }
            q=tmp->next;
        }
        //seperate list
        RandomListNode *dupHead = head == NULL ? NULL : head->next, *cur = head;
        while(cur){
            RandomListNode *tmp = cur->next;
            cur->next = tmp->next;
            if(tmp->next){
                tmp->next = tmp->next->next;
            }
            cur = cur->next;
        }
        return dupHead;
    }
};

 

 

相關文章