首页 > 代码库 > 链式前向星储存

链式前向星储存


#include <iostream>
#include <cstring>
using namespace std;

#define E 10000
#define V 100

struct Edge{

    int to_node;
    int edge_val;
    int next_edge;

    Edge(){}
    Edge( int to, int val, int next ){
        to_node   = to;
        edge_val  = val;
        next_edge = next;
    }
};

Edge edges[E];
int heads[V];

int nEdgeNum, nNodeNum;
int nEdgeCount;


void addEdge( int from, int to, int dist ){

    edges[nEdgeCount].to_node   = to;
    edges[nEdgeCount].edge_val  = dist;
    edges[nEdgeCount].next_edge = heads[from];
    heads[from]                 = nEdgeCount;

    nEdgeCount++;

}


void showGraph(){
    for( int i = 1; i <= nNodeNum; ++i ){

        cout << i;

        for( int j = heads[i]; ~j; j = edges[j].next_edge ){
            cout << "-->" << edges[j].to_node << "(" << edges[j].edge_val << ")";
        }
        
        cout << "-->NULL" << endl;
        
    }
}


int main(){

    int from, to, dist;

    while( cin >> nNodeNum >> nEdgeNum ){

        memset( heads, -1, sizeof( heads ) );

        for( int i = 1; i <= nEdgeNum; ++i ){

            cin >> from >> to >> dist;

            addEdge( from, to, dist );

        }

        showGraph();

    }

    return 0;
}


链式前向星储存