Chinaunix首页 | 论坛 | 博客
  • 博客访问: 426682
  • 博文数量: 103
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 971
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-11 17:22
文章分类
文章存档

2008年(77)

2007年(26)

我的朋友

分类: C/C++

2007-12-19 23:07:36

#include <stdio.h>
#include <stdlib.h>

#define MAX 10

typedef struct node{
        int adjvex;
        int weight;
        struct node* next;
}edgenode;//边表结点


typedef struct vnode{
        int vertex;
        edgenode* firstedge;
}vertexnode;//顶点表结点


typedef vertexnode adj_list[MAX];//adj_list是邻接表类型

typedef struct adjlist_graph{
        int nodes, edges;//图中顶点数和边数

        adj_list adjlist;//邻接表

}algraph;

static void create_algraph(algraph* g);//建立无向图的邻接表

static void pr_algraph(algraph* g);//输出邻接表


int main(int argc, char** argv)
{
        algraph* g;

        g = (algraph* )malloc(sizeof(algraph));
        printf("begin create algraph\n");
        create_algraph(g);
        printf("finish create algraph\n");

        printf("the algraph is:\n");
        pr_algraph(g);

        exit(0);
}

static void create_algraph(algraph* g)
{
        edgenode* newnode;
        int i, j, k;

        printf("please input node number and edge number: ");
        scanf("%d%d", &g->nodes, &g->edges);
        printf("node number = %d, edges = %d\n", g->nodes, g->edges);

        for(i = 0; i < g->nodes; i++){
                g->adjlist[i].vertex = i;
                g->adjlist[i].firstedge = NULL;
        }

        for(k = 0; k < g->edges; k++){
                printf("please input new edge: ");
                scanf("%d%d", &i, &j);
                printf("\n");

                newnode = (edgenode* )malloc(sizeof(edgenode));
                newnode->adjvex = j;
                newnode->weight = 0;
                newnode->next = g->adjlist[i].firstedge;
                g->adjlist[i].firstedge = newnode;

                newnode = (edgenode* )malloc(sizeof(edgenode));
                newnode->adjvex = i;
                newnode->weight = 0;
                newnode->next = g->adjlist[j].firstedge;
                g->adjlist[j].firstedge = newnode;
        }
}

static void pr_algraph(algraph* g)
{
        edgenode* node;
        int i;

        for(i = 0; i < g->nodes; i++){
                node = g->adjlist[i].firstedge;
                printf("g->adjlist[%d] = %d: ", i, g->adjlist[i].vertex);
                while(node != NULL){
                        printf("%d %d\t", node->adjvex, node->weight);
                        node = node->next;
                }
                printf("\n");
        }
}

阅读(12378) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-06-19 01:23:13

chinaunix网友2009-11-18 17:48:42

写的太好了!