您的位置:首页 > 运维架构

LeetCode-138.Copy List with Random Pointer

2016-07-02 21:05 288 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 leetcode