Leetcode 138. Copy List with Random Pointer

#include <iostream>
using namespace std;
struct RandomListNode {
    int label;
    RandomListNode *next, *random;
    RandomListNode(int x) : label(x), next(NULL), random(NULL) {}

};
RandomListNode *copyRandomList(RandomListNode *head) {
    RandomListNode *str = head;
    RandomListNode *newNode = NULL;
    if (str == NULL)
        return NULL;
    while (str != NULL)
    {
        RandomListNode *newNode = new RandomListNode(0);
        newNode->label = str->label;
        newNode->next = str->next;
        RandomListNode *temp = str->next;
        str->next = newNode;
        str = temp;
    }
    str = head;
    while (str) {
        str->next->random = str->random ? str->random->next : nullptr;
        str = str->next->next;
    }
    str = head;
    RandomListNode *temp = NULL;
    RandomListNode *newLink = str->next;
    newNode = str->next;
    while (str != NULL&&str->next != NULL)
    {
        temp = str->next;
        str->next = temp->next;
        /*if (temp->next != NULL) temp->next = temp->next->next; else temp->next = NULL;*/
        temp->next = temp->next ? temp->next->next : nullptr;
        str = str->next;
    }
    return newLink;
}
//进行测试
int main()
{
    RandomListNode *p1 = new RandomListNode(1);
    RandomListNode *p2 = new RandomListNode(2);
    RandomListNode *p3 = new RandomListNode(3);
    p1->next = p2; p2->next = p3; p3->next = nullptr;
    p1->random = p3;
    p2->random = nullptr;
    p3->random = p2;
    RandomListNode *newlink;
    newlink = copyRandomList(p1);
    while (newlink != nullptr)
    {
        cout << newlink->label << endl;
        newlink = newlink->random;
    }
}

你可能感兴趣的:(LeetCode)