From 43b237487af776567bfd4328d66a914d4df9ff88 Mon Sep 17 00:00:00 2001 From: jf-home Date: Sat, 26 Apr 2025 16:02:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A0=E8=BE=B9=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E6=B2=A1=E6=9C=89=E8=A2=AB=E5=8E=8B=E5=88=B0=E6=A0=88=E4=B8=AD?= =?UTF-8?q?=E5=8E=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/graph.c | 37 +++++++++++++++++++++++++++++++++++++ test/test_graph.c | 20 +++++++++++++++----- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/graph.c b/src/graph.c index 47e0222..060d440 100644 --- a/src/graph.c +++ b/src/graph.c @@ -899,6 +899,43 @@ const void *graph_iter_next(struct _iterator *iter) case GRAPH_DFS: { // self->stack->push(self->stack, iter->_cur_node); + struct _graph_node* cur_node = self->_iter._cur_node; + struct _graph_node* node = NULL; + struct _graph_edge *cur_edge = cur_node->edgehead; + struct _graph_node *target = NULL; + + stack_t stack = self->stack; + + while (!self->stack->empty(self->stack) || cur_node != NULL) + { + if (cur_edge != NULL) + { + target = cur_edge->target; + if(target != NULL && target->visited != true) + { + stack->push(stack, &target); + } + cur_edge = cur_edge->next; + } + else + { + iterator_t iter = stack->iter(stack); + while(iter->hasnext(iter)) + { + struct _graph_node* g_node = *(struct _graph_node **)iter->next(iter); + self->print_obj(g_node->obj); + } + printf("\n"); + + self->stack->pop(self->stack, &cur_node); + node = cur_node; + cur_node = cur_node->next; + break; + } + } + + iter->_cur_node = node; + obj = cur_node->obj; } break; default: diff --git a/test/test_graph.c b/test/test_graph.c index 3df66f4..5f95869 100644 --- a/test/test_graph.c +++ b/test/test_graph.c @@ -146,17 +146,27 @@ void test_graph_iter(void) TEST_ASSERT_TRUE(graph->add_edge(graph, &data[1], &data[3], 24)); TEST_ASSERT_TRUE(graph->add_edge(graph, &data[5], &data[6], 67)); - TEST_ASSERT_TRUE(graph->add_edge(graph, &data[7], &data[6], 24)); - TEST_ASSERT_TRUE(graph->add_edge(graph, &data[9], &data[2], 67)); + TEST_ASSERT_TRUE(graph->add_edge(graph, &data[7], &data[6], 87)); + TEST_ASSERT_TRUE(graph->add_edge(graph, &data[8], &data[2], 92)); TEST_ASSERT_FALSE(graph->add_edge(graph, &temp, &data[1], 0)); - graph->print(graph); + // graph->print(graph); - iterator_t iter_vertex = graph->iter(graph, GRAPH_BFS, &data[0]); + iterator_t iter_vertex = NULL; + + iter_vertex = graph->iter(graph, GRAPH_BFS, &data[0]); TEST_ASSERT_NOT_NULL(iter_vertex); while(iter_vertex->hasnext(iter_vertex)) { temp = *(int *)iter_vertex->next(iter_vertex); - graph->print_obj(&temp); + // graph->print_obj(&temp); + } + + iter_vertex = graph->iter(graph, GRAPH_DFS, &data[0]); + TEST_ASSERT_NOT_NULL(iter_vertex); + while(iter_vertex->hasnext(iter_vertex)) + { + temp = *(int *)iter_vertex->next(iter_vertex); + // graph->print_obj(&temp); } graph_free(&graph);