目前edge打印还是有错误,from和to的顶点不对

This commit is contained in:
建峰 2025-04-25 16:32:11 +08:00
parent c3ed2ab00d
commit 7ad5631aec
2 changed files with 23 additions and 37 deletions

View File

@ -625,9 +625,7 @@ static bool graph_add_edge(struct _graph* self, void* from, void* to, uint32_t w
return false; return false;
} }
// add edge // from_node add edge
if (from_node->edge == NULL)
{
struct _graph_edge* new_edge = graph_edge_new(); struct _graph_edge* new_edge = graph_edge_new();
if (new_edge == NULL) if (new_edge == NULL)
{ {
@ -636,45 +634,33 @@ static bool graph_add_edge(struct _graph* self, void* from, void* to, uint32_t w
new_edge->weight = weight; new_edge->weight = weight;
new_edge->target = to_node; new_edge->target = to_node;
if (from_node->edge == NULL)
{
from_node->edge = new_edge; from_node->edge = new_edge;
} }
else else
{ {
struct _graph_edge* new_edge = graph_edge_new();
if (new_edge == NULL)
{
return false;
}
new_edge->weight = weight;
new_edge->target = to_node;
new_edge->next = from_node->edge->next; new_edge->next = from_node->edge->next;
from_node->edge->next = new_edge; from_node->edge->next = new_edge;
} }
// if graph is undirected // if graph is undirected
if (to_node->edge == NULL) struct _graph_edge* new_edge2 = graph_edge_new();
{ if (new_edge2 == NULL)
to_node->edge = graph_edge_new();
if (to_node->edge == NULL)
{ {
return false; return false;
} }
to_node->edge->weight = weight; new_edge2->weight = weight;
to_node->edge->target = from_node; new_edge2->target = from_node;
if (to_node->edge == NULL)
{
to_node->edge = new_edge2;
} }
else else
{ {
struct _graph_edge* new_edge = graph_edge_new(); new_edge2->next = to_node->edge->next;
if (new_edge == NULL) to_node->edge->next = new_edge2;
{
return false;
}
new_edge->weight = weight;
new_edge->target = from_node;
new_edge->next = to_node->edge->next;
to_node->edge->next = new_edge;
} }
return true; return true;

View File

@ -92,9 +92,9 @@ void test_graph_add_edge(void)
graph->print(graph); graph->print(graph);
// test add_edge // test add_edge
TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[1], 0)); TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[1], 55));
TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[2], 0)); // TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[2], 66));
TEST_ASSERT_TRUE(graph->add_edge(graph, &data[1], &data[3], 0)); // TEST_ASSERT_TRUE(graph->add_edge(graph, &data[1], &data[3], 77));
graph->print(graph); graph->print(graph);
TEST_ASSERT_FALSE(graph->add_edge(graph, &temp, &data[1], 0)); TEST_ASSERT_FALSE(graph->add_edge(graph, &temp, &data[1], 0));