#include<iostream> using namespace std; #define MAX_NODE 30 #define MAX_INFO 10 bool isOutput[MAX_NODE]; //記錄該節點有沒有輸出 struct ListNode { ListNode(){next=NULL;} int position; ListNode* next; }; struct VertexNode { VertexNode() { head=NULL; inDegree=0; } int currentPosition; //當前節點在圖存儲結構中數組的位置 int inDegree; //該節點的入度 char info[MAX_INFO]; //該節點的信息 ListNode* head; //該節點相鄰節點的第一個節點 }; struct Graphic { int vertex,edge; VertexNode vers[MAX_NODE]; }; void createGraphic(Graphic& graphic) { cout<<"請輸入節點數和邊數: "; cin>>graphic.vertex>>graphic.edge; cout<<"請輸入節點信息:"<<endl; int i; for(i=0;i<graphic.vertex;i++) { cout<<"請輸入第"<<i<<"個節點信息:"; cin>>graphic.vers[i].info; } cout<<"請輸入邊信息:"<<endl; int first=0; int second=0; for(i=0;i<graphic.edge;i++) { cout<<"請輸入第"<<i<<"條邊信息:"; cin>>first>>second; ListNode* temp=new ListNode; temp->position=second; temp->next=graphic.vers[first].head; graphic.vers[first].head=temp; ++graphic.vers[second].inDegree; } for(i=0;i<graphic.vertex;i++) { isOutput[i]=false; } for(i=0;i<graphic.vertex;i++) { graphic.vers[i].currentPosition=i; } } void printGraphic(Graphic graphic) { int i; ListNode* temp=NULL; for(i=0;i<graphic.vertex;i++) { cout<<graphic.vers[i].info<<"--->"; temp=graphic.vers[i].head; if(!temp) { cout<<"NULL"; } while(temp) { cout<<temp->position<<" "; temp=temp->next; } cout<<endl; } for(i=0;i<graphic.vertex;i++) { cout<<"節點"<<i<<"的入度:"; cout<<graphic.vers[i].inDegree<<endl; } cout<<endl; } VertexNode* findZeroInDegreeNode(Graphic& graphic) { int i; for(i=0;i<graphic.vertex;i++) { if(graphic.vers[i].inDegree==0) { graphic.vers[i].inDegree=1; return &graphic.vers[i]; } } return NULL; } void TopologicalSortForVertex(Graphic& graphic,int position) { ListNode* head=graphic.vers[position].head; while(head) { if(!isOutput[head->position]) { cout<<graphic.vers[head->position].info<<" "; isOutput[head->position]=true; } TopologicalSortForVertex(graphic,head->position); head=head->next; } } void TopologicalSort(Graphic& graphic) { VertexNode* zeroNode=findZeroInDegreeNode(graphic); if(!zeroNode) return; if(!isOutput[zeroNode->currentPosition]) { cout<<zeroNode->info<<" "; isOutput[zeroNode->currentPosition]=true; } TopologicalSortForVertex(graphic,zeroNode->currentPosition); TopologicalSort(graphic); } void main() { Graphic myGraphic; createGraphic(myGraphic); printGraphic(myGraphic); TopologicalSort(myGraphic); }