图 邻接表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <limits.h>

#define MAX_VERTEX_NUM 20

typedef int VertexType;


typedef struct node{
    VertexType adjvex;
    int weight; //权值
    struct node *next;
}EdgeNode;

typedef struct vnode{
    VertexType vertex;  //顶点域
    EdgeNode *firstedge;
}VertexNode;

typedef VertexNode AdjList[MAX_VERTEX_NUM];

typedef struct{
    AdjList adjlist;
    int n,e;    //顶点数和边数
}ALGraph;
/*
int Locate(ALGraph *G, int n){
    int i;
    for(i=0; i<G->n; i++){
        if(G->adjlist[i].vertex == n) return i;
    }
    return -1;
}*/

void CreateALGraph(ALGraph *G){//建立有向图的邻接表
    int i,j;
    int k;
    EdgeNode *s;
    scanf("%d%d", &G->n, &G->e);
    for(i=0; i<G->n; i++){
        scanf("%d", &G->adjlist[i].vertex);//G->adjlist[i].vertex = getch();
        G->adjlist[i].firstedge = NULL; //边表设置成空表
    }
    for(k=0; k<G->e; k++){
        scanf("%d%d", &i, &j);
    //    i = Locate(G, i); j = Locate(G, j); //查找结点序号
        s = (EdgeNode *)malloc(sizeof(EdgeNode));
        scanf("%d", &s->weight);
        s->adjvex = j;  //邻接点序号为j
        s->next = G->adjlist[i].firstedge;
        G->adjlist[i].firstedge = s;

        //无向图时加上
     //   s = (EdgeNode *)malloc(sizeof(EdgeNode));
     //   s->adjvex = i;
     //   s->next = G->adjlist[j].firstedge;
     //   G->adjlist[j].firstedge = s;
    }
}

void print(ALGraph *G){
    EdgeNode *p;
    int i;
    for(i=0; i<G->n; i++){
        printf("index %d VERTEX %d", i, G->adjlist[i].vertex);
        for(p = G->adjlist[i].firstedge; p; p = p->next){
            printf("->\tVERTEX %d weight %d", p->adjvex, p->weight);
        }
        putchar('\n');
    }
}

int main(){
    freopen("d:\\my.txt", "r", stdin);
    ALGraph G;
    CreateALGraph(&G);
    print(&G);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值