标签:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<stack> using namespace std; #define MAX 20 typedef struct node { struct node * nextarc; char Info; }ArcNode, *pArcNode; typedef struct { int VerCount;//顶点数目 int ArcCount; //弧的数目 pArcNode Adj; }AdjList, *pAdjList; void CreatAdj(pAdjList myAdjList,int *sign) { int i, j; char tail; pArcNode p, q; printf("Please input the num of Vertex:");//顶点个数 scanf("%d", &myAdjList->VerCount); printf("Pleaase input the num of Arc");//弧的个数 scanf("%d", &myAdjList->ArcCount); myAdjList->Adj = (pArcNode)malloc(myAdjList->VerCount *sizeof(ArcNode)); for (i = 0; i < myAdjList->VerCount; i++) myAdjList->Adj[i].nextarc = NULL; printf("Please input the Graph: \n"); printf("Please input all of the vertex:\n"); fflush(stdin); for (i = 0; i < myAdjList->VerCount; i++) { scanf("%c", &myAdjList->Adj[i].Info); fflush(stdin); } printf("Please input the Ver:\n"); for (i = 0; i < myAdjList->ArcCount; i++) { printf("Please input tail of Arc%d :", i); scanf("%c", &tail); p = (pArcNode)malloc(sizeof(ArcNode)); p->nextarc = NULL; fflush(stdin); printf("Please input head of Arc%d :", i); scanf("%c", &p->Info); getchar(); for (j = 0; j < myAdjList->VerCount; j++) if (myAdjList->Adj[j].Info == p->Info) sign[j]++; for (j = 0; j < myAdjList->VerCount; j++) { if (myAdjList->Adj[j].Info == tail) { q = &myAdjList->Adj[j]; while (q->nextarc != NULL) q = q->nextarc; q->nextarc = p; } } } } void TopologicalSort(pAdjList myAdjList, int *sign) { stack <ArcNode> S; ArcNode *temp; int s[10]; int i, j; for (i = 0; i < myAdjList->VerCount; i++) s[i] = sign[i]; for (i = 0; i < myAdjList->VerCount; i++) { if (s[i] == 0) { S.push(myAdjList->Adj[i]); s[i] = -1; } } while (!S.empty()) { for (i = 0; i < myAdjList->VerCount; i++) if (myAdjList->Adj[i].Info == S.top().Info) temp = &myAdjList->Adj[i]; S.pop(); printf("%c", temp->Info); while (temp->nextarc != NULL) { for ( j = 0; j < myAdjList->VerCount; j++) { if (myAdjList->Adj[j].Info == temp->nextarc->Info) { s[j]--; if (s[j] == 0) { S.push(myAdjList->Adj[j]); s[j] = -1; } } } temp = temp->nextarc; } } } int main() { AdjList myAdjList; int sign[10]; for (int i = 0; i < 10; i++) sign[i] = 0; CreatAdj(&myAdjList,sign); TopologicalSort(&myAdjList, sign); system("pause"); return 0; }
栈操作。
标签:
原文地址:http://www.cnblogs.com/da-peng/p/5004633.html