Recursion 如何将使用递归的深度优先遍历代码转换为使用堆栈的代码?
我的数据结构和堆栈操作是这样定义的Recursion 如何将使用递归的深度优先遍历代码转换为使用堆栈的代码?,recursion,data-structures,graph,stack,traversal,Recursion,Data Structures,Graph,Stack,Traversal,我的数据结构和堆栈操作是这样定义的 typedef struct AdjListNode{ int dest; struct AdjListNode* next; int visited; }AdjListNode; typedef struct AdjList{ struct AdjListNode* head; }AdjList; typedef struct Graph{ int V; struct AdjList* array; }Gr
typedef struct AdjListNode{
int dest;
struct AdjListNode* next;
int visited;
}AdjListNode;
typedef struct AdjList{
struct AdjListNode* head;
}AdjList;
typedef struct Graph{
int V;
struct AdjList* array;
}Graph;
typedef struct Stack{
int top;
char items[MAX];
}Stack;
void Push(struct Stack *s,float val){
if(s->top == MAX-1){
printf("Error: Stack overflow.");
exit(1);
}else{
s->items[++(s->top)]=val;
}
}
float Pop(struct Stack *s){
if(s->top == -1){
printf("Error: Stack underflow");
exit(1);
}else{
return(s->items[(s->top)--]);
}
}
int isFull(struct Stack* s){
return s->top == MAX-1;
}
int isEmpty(struct Stack* s){
return s->top == -1;
}
这个函数检查是否有从p到q的路径
void FindPath_DepthFirstSearch(Graph* graph, int p, int q) {
AdjListNode* node = graph->array[p].head;
node->visited = 1;
// printf("%d\n", p);
if(p == q){
printf("Path found!\n");
exit(1);
}
while(node){
if (!graph->array[node->dest].head->visited)
FindPath_DepthFirstSearch(graph, node->dest, q);
node = node->next;
}
printf("Path not found!\n");
exit(1);
}
我对学习数据结构相当陌生。当我使用递归时,代码可以完美地工作,但是当我尝试使用堆栈实现这个时,我被困了很长一段时间。有人能帮我吗?谢谢 从递归定义转换为基于循环的定义时,基本思想是将通常存储在堆栈(LIFO)容器上局部变量中的数据存储。不是递归,而是将其他元素推送到堆栈上。代码如下所示:
function algorithm(args):
stack = new FIFO
# push initial state (e.g. root node for DFS)
stack.push(args)
# process all elements
while stack.has_elements():
# retrieve topmost element from stack
e = stack.pop()
# do something with the current element
e.frobnicate()
# push additional elements onto the stack
if e.condition1():
stack.push(e.derived1())
if e.condition2():
stack.push(e.derived2())