1032. Sharing (25)

本文介绍了一种使用链表进行数据存储的方法,并通过构建链表来查找两个链表中的共同节点。主要实现了链表的创建、遍历、释放及相同子链表的搜索功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

考察链表以及相同子链表的搜索记录

#include<iostream>
#include<map>
#include<vector>
#include<set>

typedef struct Node
{
	int adress;
	Node* next;
	Node(int _a = 0, Node* _next = NULL):adress(_a),next(_next){};
}Node, *PNode;

void ReleaseList(Node* list)
{
	while(list)
	{
		Node* pNext = list->next;
		delete list;
		list = pNext;
	}
}

int FindCommonIndex(Node* list1, Node* list2)
{
	int res = -1;
	std::set<int> set;
	while(list1)
	{
		set.insert(list1->adress);
		list1 = list1->next;
	}
	std::set<int>::iterator it;
	while(list2)
	{
		it=set.find(list2->adress);
		if(it != set.end())
		{
			res = list2->adress;
			break;
		}
		list2 = list2->next;
	}
	return res;
}
void BuildList(Node* &list, std::map<int, int>& map)
{
	std::map<int, int>::iterator it;
	int key = list->adress;
	it=map.find(key);
	Node** p = &list->next;
	while(it != map.end())
	{
		(*p) = new Node;
		(*p)->adress = (*it).second;
		key = (*p)->adress;
		it=map.find(key);
		p = &(*p)->next;
	}
}
int main()
{
	int s1, s2, n;
	while( scanf("%d%d%d", &s1, &s2, &n) != EOF )
	{
		int a, b;
		char c;
		std::map<int, int> map;
		for(int i = 0; i < n; ++i)
		{
			scanf("%d%*c%c%d", &a, &c, &b);
			map[a] = b;
		}
		Node* list1 = new Node;
		list1->adress = s1;
		Node* list2 = new Node;
		list2->adress = s2;
		//build list
		BuildList(list1, map);
		BuildList(list2, map);
		//find common index
		int comIdx = FindCommonIndex(list1, list2);
		//release
		ReleaseList(list1);
		ReleaseList(list2);

		if(comIdx == -1)
			printf("-1\n");
		else 
			printf("%05d\n", comIdx);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值