Login
C- Kod
347 просмотров
Перейти к просмотру всей ветки
scorpi_ скептик
in Antwort lena12345 06.03.07 17:25
Кто ж это над вами так издевается, что заставляет в голом С писать?
Двусвязный список здесь собственно не нужен, можно и односвязным. А можно и массивами, например так:
При этом мы исходим из того, что файл с графом выглядит так:
например
При этом вместо названий городов должны собственно стоять цифры.
Двусвязный список здесь собственно не нужен, можно и односвязным. А можно и массивами, например так:
В ответ на:
struct Edge
{
int target;
int weight;
};
struct Node
{
int node_id;
int edge_number;
Edge* edges;
};
struct graph
{
int node_number;
Node* nodes;
} graph_;
void read_nodes( FILE * graph_file )
{
int node_index, edge_index;
for( node_index = 0; node_index < graph_.node_number; ++node_index )
{
struct Node *node = graph_.nodes[node_index];
if ( 3 != fscanf( graph_file, "%i%i", &node->node_id, &node->edge_number ) ) {
printf( "Syntaxfehler in Graph-Datei - Fehlerhafter Knoteneintrag" );
exit( EXIT_FAILURE );
}
node->edges = ( struct Edge* ) calloc( node->edge_number * sizeof( struct Edge ) );
if ( ! node->edges ) {
printf( "Fehler bei Speicherreservierung" );
exit( EXIT_FAILURE );
}
for( edge_index = 0; edge_index < node->edge_number; ++edge_index )
{
struct Edge *edge = &node->edges[ edge_index ];
if ( 2 != fscanf( graph_file, "%i%i", &edge->target, &edge->weight ) ) {
printf( "Syntaxfehler in STG-Datei - Fehlerhafter Vorgängereintrag" );
exit( EXIT_FAILURE );
}
}
}
}
void read_graph_file( const char* filename )
{
FILE *graph_file = fopen( filename, "r" );
if ( ! graph_file ) {
printf( "Can't open graph-file" );
exit( EXIT_FAILURE );
}
if ( 1 != fscanf( graph_file, "%i", &graph_.node_number ) ) {
printf( "Can't read number of nodes" );
exit( EXIT_FAILURE );
}
graph_.Nodes = (struct Nodes*) calloc( graph_.node_number, sizeof(struct Node) );
if ( ! graph_.nodes ) {
printf( "Can't allocate memory for nodes" );
exit( EXIT_FAILURE );
}
read_nodes( graph_file );
fclose( graph_file );
}
При этом мы исходим из того, что файл с графом выглядит так:
В ответ на:
NodeNumber
NodeA EdgeNumber EdgeA WeightA EdgeB WeightB
NodeB EdgeNumber EdgeA WeightA
например
В ответ на:
3
Berlin 2 Kiel 400 Hannover 250
Hannover 1 Kiel 250
Kiel 0
При этом вместо названий городов должны собственно стоять цифры.