#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);
}
哪里不懂可以提问哦