[leetcode] 138. Copy List with Random Pointer 解题报告

题目链接:https://leetcode.com/problems/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.


思路:这题是要做一个深copy,可以先建立好链表,然后再连random的指针。因为random的指针是随机的,所以在找新的每一个结点的random指针指向的结点的时候可以让新的链表和原来的链表每次从头同步走,直到碰到原来链表random指针指向的结点停止,然后将新链表的一个结点random指针指向走到的地方。时间复杂为O(n*n)。

理解了题意应该还是很容易能想到怎么做的。链表23题刷完了,下一个就二叉树吧大笑

代码如下:

/**
 * 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) return head;
        RandomListNode *p = head, *pHead = new RandomListNode(0), *q = pHead;
        while(p)
        {
            RandomListNode *tem = new RandomListNode(p->label);
            q->next = tem;
            q = tem;
            p = p->next;
        }
        q = pHead->next;
        p = head;
        while(p)
        {
            RandomListNode* temP = head;
            RandomListNode* temQ = pHead->next;
            while(temP && p->random != temP)
            {
                temP = temP->next;
                temQ = temQ->next;
            }
            q->random = temQ;
            
            q = q->next;
            p = p->next;
        }
        return pHead->next;
    }
};



你可能感兴趣的:(LeetCode,链表)