剑指offer:复杂链表的复制

//剑指offer:复杂链表的复制(复制一个包含random域的链表,random域随机的指向链表中任意节点)
//思路:先复制出链表的next结构并且将自己对应的值和自身放入map中
//      再复制random域,通过将之前链表的random域的值取出来,然后去map中找新链表对应的结点,并赋值。
//      注意不要错误的使用之前的链表节点。画图让思路更清楚。

#include "stdafx.h"
#include"map"
using namespace std;
struct RandomListNode {
	int label;
	struct RandomListNode *next, *random;
	RandomListNode(int x) :
		label(x), next(NULL), random(NULL) {
	}
};

RandomListNode* Clone(RandomListNode* pHead)
{
	if (pHead == NULL)
		return NULL;
	RandomListNode* clon = pHead;
	RandomListNode* clon_head = NULL;
	RandomListNode* last_node = NULL;
	map<int, RandomListNode*> ma;
	while (clon != NULL) {
		RandomListNode *tmp = new RandomListNode(clon->label);
		if (clon_head == NULL) {
			clon_head = tmp;
		}
		if (last_node != NULL)
			last_node->next = tmp;
		last_node = tmp;
		ma.insert(make_pair(tmp->label, tmp));
		//tmp->random = clon->random;
		clon = clon->next;
	}
	clon = clon_head;
	RandomListNode *clon2 = pHead;
	while (clon != NULL) {


		/*tmp->next = clon->next;         //这里错误的使用了以前链表的结点
		tmp->random = ma[clon->label];
		clon = clon->next; */
		if (clon2->random != NULL)
			clon->random = ma[clon2->random->label];
		clon2 = clon2->next;
		clon = clon->next;

	}
	return clon_head;
}

int main()
{
	RandomListNode *head = NULL;
	RandomListNode *test = NULL;
	RandomListNode *tmp = NULL;
	for (int i = 0; i < 5; i++) {
		
		tmp = new RandomListNode(i);

		if (test != NULL)
			test->next = tmp;
		test = tmp;
		if (i == 0)
			head = tmp;
		
	}
	for (int j = 0; j < 5; j++) {
		RandomListNode *node = head;
		for (int z = 0; z < j; z++)
			node = node->next;
		tmp = node;
		if (tmp->next == NULL)
			tmp = head;
		else
			tmp = tmp->next;
		if (tmp->next == NULL)
			tmp = head;
		else
			tmp = tmp->next;
		node->random = tmp;
	}
	RandomListNode *temp = head;
	while (temp) {
		printf("%d %d\n", temp->label, temp->random->label);
		temp = temp->next;
	}
	
	RandomListNode *head2 = Clone(head);
	
	while (head2) {
		printf("%d %d\n", head2->label,head2->random->label);
		head2 = head2->next;
	}
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值