【LeetCode】138. Copy List with Random Pointer

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.

 

BFS遍历链表,类似树的层次遍历,进行深度复制。

/**
 * 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) {
        //BFS
        if(head == NULL)
            return NULL;
        unordered_map<RandomListNode*, RandomListNode*> m;
        unordered_map<RandomListNode*, bool> visited;
        queue<RandomListNode*> q;
        q.push(head);
        visited[head] = true;
        while(!q.empty())
        {
            RandomListNode* front = q.front();
            q.pop();
            RandomListNode* copyfront;
            if(m.find(front) == m.end())
            {
                copyfront = new RandomListNode(front->label);
                m[front] = copyfront;
            }
            else
                copyfront = m[front];
            if(front->random)
            {
                RandomListNode* random = front->random;
                if(visited[random] == false)
                {
                    q.push(random);
                    visited[random] = true;
                }
                RandomListNode* copyrandom;
                if(m.find(random) == m.end())
                {
                    copyrandom = new RandomListNode(random->label);
                    m[random] = copyrandom;
                }
                else
                    copyrandom = m[random];
                copyfront->random = copyrandom;
            }
            if(front->next)
            {
                RandomListNode* next = front->next;
                if(visited[next] == false)
                {
                    q.push(next);
                    visited[next] = true;
                }
                RandomListNode* copynext;
                if(m.find(next) == m.end())
                {
                    copynext = new RandomListNode(next->label);
                    m[next] = copynext;
                }
                else
                    copynext = m[next];
                copyfront->next = copynext;
            }
        }
        return m[head];
    }
};

 

posted @ 2014-11-18 14:41  陆草纯  阅读(223)  评论(0编辑  收藏  举报