不得不说网上的真的是太乱了,看得我脑壳疼 自己写的可以,感觉好的话可以当成模板。
有向图
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;
#define maxn 200
int v, e;
typedef struct _Enode
{
int ivex;
int value;
struct _Enode* next_edge;
}ENode,*PENode;
typedef struct _VNode
{
int data;
ENode* fidt_edge;
}VNode;
typedef struct _LGraph
{
int vex_num;
int edg_num;
VNode vexs[maxn];
}LGraph;
LGraph* create()
{
LGraph* pG;
pG = (LGraph*)malloc(sizeof(LGraph));
memset(pG, 0, sizeof(LGraph));
pG->vex_num = v;
pG->edg_num = e;
for (int i = 0; i < v; ++i)
pG->vexs[i].fidt_edge = NULL;
for (int i = 0; i < e; ++i)
{
int v1, v2;
scanf_s("%d%d", &v1, &v2);
ENode* p1 = (ENode*)malloc(sizeof(ENode));
p1->ivex = v2;
p1->next_edge = pG->vexs[v1].fidt_edge;
pG->vexs[v1].fidt_edge = p1;
}
return pG;
}
int main()
{
while (~scanf_s("%d%d", &v, &e))
{
if (v == 0 && e == 0)
break;
LGraph* pG;
pG = create();
}
return 0;
}
无向图
在代码的建立链表的地方变成
for (int i = 0; i < e; ++i)
{
int v1, v2;
scanf_s("%d%d", &v1, &v2);
ENode* p1 = (ENode*)malloc(sizeof(ENode));
p1->ivex = v2;
p1->next_edge = pG->vexs[v1].fidt_edge;
pG->vexs[v1].fidt_edge = p1;
ENode* p2 = (ENode*)malloc(sizeof(ENode));
p2->ivex = v1;
p2->next_edge = pG->vexs[v2].fidt_edge;
pG->vexs[v2].fidt_edge = p2;
}
邻接表存图进行拓扑排序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;
#define maxn 200
int v, e;
typedef struct _Enode
{
int ivex;
struct _Enode* next_edge;
}ENode,*PENode;
typedef struct _VNode
{
int data;
int indegree;
ENode* fidt_edge;
}VNode;
typedef struct _LGraph
{
int vex_num;
int edg_num;
VNode vexs[maxn];
}LGraph;
LGraph* create()
{
LGraph* pG;
pG = (LGraph*)malloc(sizeof(LGraph));
memset(pG, 0, sizeof(LGraph));
pG->vex_num = v;
pG->edg_num = e;
for (int i = 0; i < v; ++i)
pG->vexs[i].fidt_edge = NULL;
for (int i = 0; i < e; ++i)
{
int v1, v2;
scanf_s("%d%d", &v1, &v2);
ENode* p1 = (ENode*)malloc(sizeof(ENode));
p1->ivex = v2;
p1->next_edge = pG->vexs[v1].fidt_edge;
pG->vexs[v1].fidt_edge = p1;
}
return pG;
}
void TopSort(LGraph* pG)
{
stack<int>s;
int count, k, i;
ENode* p;
for (int i = 0; i < v; ++i)
{
p = pG->vexs[i].fidt_edge;
while (p)
{
pG->vexs[p->ivex].indegree++;
p = p->next_edge;
}
}
for (int i = 0; i < v; ++i)
if (pG->vexs[i].indegree == 0)s.push(i);
count = 0;
while (!s.empty())
{
int k = s.top();
s.pop();
++count;
for (p = pG->vexs[k].fidt_edge; p; p = p->next_edge)
{
int to;
to = p->ivex;
pG->vexs[to].indegree--;
if (pG->vexs[to].indegree == 0)
s.push(to);
}
}
if (count < pG->vex_num)
printf("NO\n");
else
printf("YES\n");
}
int main()
{
while (~scanf_s("%d%d", &v, &e))
{
if (v == 0 && e == 0)
break;
LGraph* pG;
pG = create();
TopSort(pG);
}
return 0;
}
|