大二数据结构(图的深度遍历的 非递归算法)
发布日期:2021-05-07 23:24:20 浏览次数:13 分类:原创文章

本文共 1869 字,大约阅读时间需要 6 分钟。

#include <stdio.h>#include <stdlib.h>#define maxSize 20 typedef struct ArcNode{       int adjvex;    struct ArcNode *nextarc;}ArcNode; typedef struct{       char data;    struct ArcNode *firstarc;}VNode; typedef struct{       VNode adjlist[maxSize];    int n, e;}AGraph; void createGraph(AGraph *G){       int i, tail, head, edges, vertex;    ArcNode *tmp, *p;    printf("请输入图的顶点数:");    scanf("%d", &vertex);    printf("请输入图的边数:");    scanf("%d", &edges);        G->n = vertex;    G->e = edges;        for (i = 1; i <= edges; ++i) {           printf("请输入第%d条边的弧尾与弧头\n", i);        printf("弧尾: ");        scanf("%d", &tail);        printf("弧头: ");        scanf("%d", &head);        p = (ArcNode *)malloc(sizeof(ArcNode));        p->adjvex = head;        p->nextarc = NULL;        //建立邻接表        tmp = G->adjlist[tail].firstarc;        if(tmp == NULL)            G->adjlist[tail].firstarc = p;        else{               while (tmp->nextarc != NULL)                tmp = tmp->nextarc;            tmp->nextarc = p;        }    }    printf("图建立完毕\n");} void DFSNonRecursion(AGraph *G, int v){       printf("图DFS开始\n");    int stack[maxSize];    int top = -1;    int visit[maxSize];    int i, j, k;    ArcNode *p;        for (i = 0; i < maxSize; ++i)        visit[i] = 0;        printf("%d  ", v);    visit[v] = 1;    stack[++top] = v;    while (top != -1) {           j = stack[top];        p = G->adjlist[j].firstarc;        while (p != NULL) {               while (p != NULL && visit[p->adjvex] == 1)                p = p->nextarc;            if(p == NULL)                break;            k = p->adjvex;            stack[++top] = k;            visit[k] = 1;            printf("%d  ", k);            p = G->adjlist[k].firstarc;        }        --top;    }    printf("\n图DFS完毕\n");} int main(){       AGraph G;    createGraph(&G);    DFSNonRecursion(&G, 0);    return 0;}
上一篇:蓝桥杯大赛(历届真题1)
下一篇:数据结构课设(线性表,栈和队列,链表,图,排序查找)

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月07日 21时52分03秒