c++拓扑排序

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define MAXSIZE 26
typedef struct node
{
	char data;
	struct node* next;
}*Node,Nodes;
typedef struct Map
{
	char node;
	Node first_next;
}Map;
typedef struct
{
	Map list[MAXSIZE];
	int counts;//结点数
}*List,Lists;

int hash_table[26];

void creat(List L)
{
	L->counts = 0;
	for (int i = 0; i < 26; i++)
	{
		L->list[i].node = '#';//初始化
	}
	cout << "请输入所有结点:" << endl;
	while (true)
	{
		char temp;
		cin >> temp;
		L->list[temp - 'a'].node = temp;
		L->list[temp - 'a'].first_next = NULL;
		L->counts++;
		if (cin.get() == '\n')
		{
			break;
		}
	}
	for (int i= 0; i<26; i++)
	{
		if (L->list[i].node != '#')//把没用的过滤掉
		{
			cout << "请输入" << L->list[i].node << "结点的所有出度:";
			while (true)
			{
				Node newnode = (Node)malloc(sizeof(Nodes));
				cin >> newnode->data;
				char mark = newnode->data;//出度值
				if (mark == '0')
				{
					break;
				}
				newnode->next = L->list[i].first_next;//头插法
				L->list[i].first_next = newnode;
				hash_table[mark - 'a']++;	//计算入度和(每输入一个出度,就相当于该出度结点的入度加1)			
				if (cin.get() == '\n')
				{
					break;
				}
			}
		}
	}
}

void Topological_Sort(List L)
{
	queue<int> q;
	vector<char> result;
	for (int i = 0; i < 26; i++)
	{
		if (L->list[i].node != '#')//把没用到得结点过滤掉,因为没用到hash_table的值也为0
		{
			if (hash_table[i] == 0)
			{
				q.push(i);
				result.push_back(L->list[i].node);
			}
		}
	}
		while (!q.empty())
		{
			char temp = q.back();
			q.pop();
			Node target = L->list[temp].first_next;
			while (target)
			{
				int num = --hash_table[target->data - 'a'];
				if (num == 0)
				{
					q.push(target->data - 'a');//如果这个结点入度为0,就进入队列
					result.push_back(target->data);
				}
				target = target->next;//在找下一个出度
			}
		}
		for (char a: result )
		{
			cout << a << " ";
		}
}
int main()
{
	List list=(List)malloc(sizeof(Lists));
	creat(list);
	Topological_Sort(list);
}

哪里不懂可以提问哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值