#include<iostream>
using namespace std;
#include<queue>
#include<stack>
typedef int vertype ;
#define max 100
int book[max];
struct ArcNode
{
int adjvex;//记录一条边的右顶点的下标
int weight;
ArcNode *next;//下一条边
};
struct VNode
{
vertype data;//顶点的类型
int in;
ArcNode *firstarc;//顶点的第一条边,是连接顶点数组与单链表的桥梁
};
struct Graph
{
int vernum;//图顶点的总个数
int arcnum;//图边的总个数
VNode ver[max];//顶点数组
};
int change(Graph *G,vertype v)
{
for(int i=1;i<=G->vernum;i++)
{
if(G->ver[i].data==v)
return i;
}
}
void creat(Graph *G)
{
cout<<"输入图的顶点数和边数"<<endl;
cin>>G->vernum>>G->arcnum ;
cout<<"输入"<<G->vernum<<"个顶点的信息"<<endl;
for(int i=1;i<=G->vernum;i++)
{
cin>>G->ver[i].data;
G->ver[i].firstarc=NULL;//初始化顶点数组和边
book[i]=0;
G->ver[i].in=0;
}
cout<<"输入"<<G->arcnum<<"个边的信息(v1,v2,weight)"<<endl;
for(int i=1;i<=G->arcnum;i++)
{
int v1,v2,weight;
int t1,t2;
cin>>t1>>t2>>weight;
v1=change(G,t1);
v2=change(G,t2);
ArcNode *node=new ArcNode;
node->adjvex=v2;//一条边的右端点
node->next=NULL;//新创建的结点初始化
node->weight=weight;
/*ArcNode *tnode=new ArcNode;
tnode->adjvex=v1;
tnode->next =NULL;
tnode->weight=weight; //这段代码加上就是无向图了
tnode->next=G->ver[v2].firstarc;
G->ver[v2].firstarc=tnode;
*/
node->next=G->ver[v1].firstarc; //这里是头插法
G->ver[v1].firstarc=node;
G->ver[v2].in++; //从v1到v2有边则v2的度数加加
/*
ArcNode *p=G->ver[v1].firstarc;//特别注意这里是v1的第一条边,v2是插入v1的第一条边或者是v1的next条边
if(p==NULL)
G->ver[v1].firstarc=node;//这里也是v1
else
{
while(p->next) / /尾插法
{
p=p->next;
}
p->next=node;
}
*/
}
}
void tuopo(Graph *G)
{
cout<<endl;
stack<int>s;
for(int i=1;i<=G->vernum;i++)
{
book[i]=0;
if(G->ver[i].in==0)
s.push(i); //首先将所有入度为0的顶点(下标)入栈
}
while(!s.empty())
{
int t=s.top(); //顶点下标出栈
s.pop();
if(book[t]==0)
cout<<G->ver[t].data<<" ";
book[t]=1;
ArcNode *p=G->ver[t].firstarc; //删边
while(p)
{
G->ver[p->adjvex].in--;
if(G->ver[p->adjvex].in==0)
{
s.push(p->adjvex);
}
p=p->next;
}
}
}
int main()
{
Graph *G=new Graph;
creat(G);
tuopo(G);
system("pause");
}
邻接表拓扑排序
Guess you like
Origin blog.csdn.net/m0_53389337/article/details/121434893
Ranking