链表-复制带随机指针的链表-中等

描述
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。 
您在真实的面试中是否遇到过这个题?  是
挑战

可否使用O(1)的空间

题目链接

程序


/**
 * 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:
    /**
     * @param head: The head of linked list with a random pointer.
     * @return: A new head of a deep copy of the list.
     */
    RandomListNode *copyRandomList(RandomListNode *head) {
        // write your code here
        //1. 在原链表的每个节点后面拷贝出一个新的节点
        if(head == NULL)
            return NULL;
        RandomListNode *cur = head;
        while(cur != NULL){
            RandomListNode *tmp = new RandomListNode(cur->label);
            tmp->next = cur->next;
            cur->next = tmp;
            cur = tmp->next;
        }
        //2. 依次给新的节点的随机指针赋值,而且这个赋值非常容易 
        //cur->next->random = cur->random->next
        cur = head;
        while(cur != NULL){
            if(cur->random != NULL)
                cur->next->random = cur->random->next;
            cur = cur->next->next;
        }
        //3. 断开链表可得到深度拷贝后的新链表
        cur = head;
        RandomListNode *res = head->next;
        while(cur != NULL){
            RandomListNode *tmp = cur->next;
            cur->next = tmp->next;
            if(tmp->next)
                tmp->next = tmp->next->next;
            cur = cur->next;
        }
        return res;
        
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80966208
今日推荐