LeetCode-138.Copy List with Random Pointer

来源:互联网 发布:java 入门 编辑:程序博客网 时间:2024/05/09 03:58

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.(《剑指Offer》P147 / 复杂链表的复制)

先忽略random节点,复制原始链表,并将每个原始节点和新复制的节点存放入map。然后通过遍历map,匹配其random节点

/** * 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 NULL;    unordered_map<RandomListNode*, RandomListNode*> table;    RandomListNode* pHead = head;    RandomListNode* headCopy = new RandomListNode(pHead->label);    table[pHead] = headCopy;    while (pHead->next)    {    RandomListNode* node = new RandomListNode(pHead->next->label);    headCopy->next = node;    table[pHead->next] = node;    pHead = pHead->next;    headCopy = headCopy->next;    }    for (auto node : table)    {    if (node.first->random)    node.second->random = table[node.first->random];    }    return table[head];    }};

不用map

1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
2、遍历链表,A1->random = A->random->next;
3、将链表拆分成原链表和复制后的链表

RandomListNode *copyRandomList(RandomListNode *head)     {        if (!head)    return NULL;    RandomListNode* pHead = head, *node;    while (head)//1->1->2->2->3->3->4->4...    {    node = new RandomListNode(head->label);    node->next = head->next;    head->next = node;    head = node->next;    }        head = pHead;    while (head)    {    if (head->random)    head->next->random = head->random->next;    head = head->next->next;    }        head = pHead;    RandomListNode* res = head->next;    while (head->next)    {    node = head->next;    head->next = node->next;    head = node;    }    return res;    }



0 0