數據結構作業之-拓撲排序(C++實現)
//張宏數據結構作業之__拓撲排序
//Get Guidance by Mr ZhangHong
//Student:abilitytao
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<stack>
using namespace std;
#define MAX 9999
stack<int>mystack;
int indegree[MAX];
struct node 

{
int adjvex;
node* next;
}adj[MAX];
int Create(node adj[],int n,int m)//鄰接表建表函數,n代表定點數,m代表邊數

{
int i;
node *p;
for(i=1;i<=n;i++)
{
adj[i].adjvex=i;
adj[i].next=NULL;
}
for(i=1;i<=m;i++)
{
cout<<"請輸入第"<<i<<"條邊:";
int u,v;
cin>>u>>v;
p=new node;
p->adjvex=v;
p->next=adj[u].next;
adj[u].next=p;
}
return 1;
}

void print(int n)//鄰接表打印函數

{
int i;
node *p;
for(i=1;i<=n;i++)
{
p=&adj[i];
while(p!=NULL)
{
cout<<p->adjvex<<' ';
p=p->next;
}
cout<<endl;
}
}
void topsort(node adj[],int n)

{
int i;
node *p;
memset(indegree,0,sizeof(indegree));
for(i=1;i<=n;i++)
{
p=adj[i].next;
while(p!=NULL)
{
indegree[p->adjvex]++;
p=p->next;
}
}
for(i=1;i<=n;i++)
{
if(indegree[i]==0)
mystack.push(i);
}
int count=0;
while(mystack.size()!=0)
{
i=mystack.top();
mystack.pop();
cout<<i<<' ';
count++;
for(p=adj[i].next;p!=NULL;p=p->next)
{
int k=p->adjvex;
indegree[k]--;
if(indegree[k]==0)
mystack.push(k);
}
}
cout<<endl;
if(count<n)cout<<"有回路"<<endl;
}


int main()

{
int n;
int m;
cout<<"請輸入頂點數及邊數:";
cin>>n>>m;
Create(adj,n,m);
cout<<"輸入的鄰接表為:"<<endl;
print(n);
cout<<"拓撲排序結果為:"<<endl;
topsort(adj,n);
system("pause");
return 0;
}
posted on 2009-04-01 17:45 abilitytao 閱讀(3822) 評論(2) 編輯 收藏 引用

