|
编译成功,但运行结果不是期望的。
[code:1]
#include <stdio.h>
#define vnum 20
typedef struct arcnode
{
int adjvex;
int info;
struct arcnode *nextarc;
} ArcNodeTp;
typedef struct vexnode
{
int vertex;
int in;
ArcNodeTp *firstarc;
} AdjList[vnum];
typedef struct linkgraph
{
AdjList adjs;
int vexnum, arcnum;
} LGraphTp;
typedef struct node
{
int data;
struct node *next;
} LStackTp;
LGraphTp* Create_LNvGraphP (LGraphTp *ga);
int main (void)
{
LGraphTp *ga;
ga = (LGraphTp *) malloc (sizeof(LGraphTp));
printf("\n有向图\n");
ga = Create_LNvGraphP(ga);
Print_LinkList(ga);
Top_Sort(ga);
}
LGraphTp* Create_LNvGraphP (LGraphTp *ga)
{
ArcNodeTp *p;
int vex, arc, vexs, arcnum;
int i, j, k;
printf("请输入顶点个数:");
scanf("%d", &vex);
printf("请输入边数个数:");
scanf("%d", &arc);
ga -> vexnum = vex;
ga -> arcnum = arc;
for (i = 0; i < vex; i++)
{
ga -> adjs[i].vertex = i + 1;
ga -> adjs[i].firstarc = NULL;
}
for (k = 0; k < arc; k++)
{
printf("请输入第%d条边的起始编号和终点编号:", k + 1);
scanf("%d %d", &i, &j);
p = (ArcNodeTp *) malloc (sizeof(ArcNodeTp));
p -> adjvex = j;
p -> nextarc = ga -> adjs[i - 1].firstarc;
ga -> adjs[i - 1].firstarc = p;
}
return (ga);
}
int Print_LinkList (LGraphTp *ga)
{
ArcNodeTp *p;
int k;
printf("\n目前输入的邻接表为:\n\n");
for (k = 0; k < ga -> vexnum; k++)
{
printf("V%d:%d |", k + 1, ga -> adjs[k].vertex);
p = ga -> adjs[k].firstarc;
while (p != NULL)
{
printf(" -> %d", p -> adjvex);
p = p -> nextarc;
}
printf("\n\n");
}
}
int InitStack(LStackTp **ls)
{
*ls = NULL;
}
int Push(LStackTp **ls, int x)
{
LStackTp *p;
p = (LStackTp *) malloc (sizeof(LStackTp));
p -> data = x;
p -> next = *ls;
*ls = p;
}
int Pop(LStackTp **ls, int *x)
{
LStackTp *p;
if (*ls != NULL)
{
p = *ls;
*x = p -> data;
*ls = (*ls) -> next;
free(p);
return 1;
}
else
return 0;
}
int EmptyStack(LStackTp **ls)
{
if (*ls == NULL)
return (1);
else
return (0);
}
int GetTop(LStackTp **ls , int *x)
{
if (*ls != NULL)
{
*x = (*ls) -> data;
return 1;
}
else
return 0;
}
int Top_Sort (LGraphTp *ga)
{
LStackTp *S;
ArcNodeTp *p;
int count, i, v;
InitStack(&S);
for (i = 0; i < ga -> vexnum; i ++)
{
if (ga -> adjs[i].in == 0)
Push(&S,i);
}
count = 0;
while (! EmptyStack(&S))
{
Pop (&S, &v);
printf("%d ", v);
count ++;
p = ga -> adjs[i].firstarc;
while (p != NULL)
{
(ga -> adjs[p -> adjvex].in) --;
if (ga -> adjs[p -> adjvex].in == 0)
Push(&S, p -> adjvex);
p = p -> nextarc;
}
}
if (count < ga -> vexnum)
{
printf("\n图中有环!\n");
return 0;
}
else
return 1;
}
[/code:1] |
|