码迷,mamicode.com
首页 > 其他好文 > 详细

Copy List with Random Pointer

时间:2015-02-05 15:01:57      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:简单的深拷贝思想,重点在于如何处理random结点,我用的是建立一个原本结点和新建结点的映射.

#include<iostream>
#include<vector>
#include<map>
using namespace std;

//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) {}
};

RandomListNode *copyRandomList(RandomListNode *head) {

	RandomListNode* TmpHead = head;
	RandomListNode* ResultList = new RandomListNode(0);
	RandomListNode* TmpResultNode = ResultList;

	map<RandomListNode*, RandomListNode*>NodeMap;
	while (TmpHead!=NULL)
	{
		RandomListNode* p = new RandomListNode(TmpHead->label);
		NodeMap.insert(make_pair(TmpHead, p));
		TmpResultNode->next = p;
		TmpResultNode = TmpResultNode->next;
		TmpHead = TmpHead->next;
	}
	TmpHead = head;
	TmpResultNode = ResultList->next;
	while (TmpHead!=NULL)
	{
		if (TmpHead->random != NULL)
			TmpResultNode->random = NodeMap[TmpHead->random];
		TmpHead = TmpHead->next;
		TmpResultNode = TmpResultNode->next;
	}
	return ResultList->next;
}


Copy List with Random Pointer

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43527629

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!