C 具有队列结构的拓扑图算法没有返回正确的顺序
经过几个小时的调试,我来到这里,寻找善良的灵魂,他们碰巧愿意深入我的问题。我正在制作一个程序,返回/打印图形的拓扑顺序,但它不会打印正确的顺序。从前置列表中删除节点时可能会出现问题 我的图形有6个节点(0到5个)和5个圆弧,如下所示:C 具有队列结构的拓扑图算法没有返回正确的顺序,c,C,经过几个小时的调试,我来到这里,寻找善良的灵魂,他们碰巧愿意深入我的问题。我正在制作一个程序,返回/打印图形的拓扑顺序,但它不会打印正确的顺序。从前置列表中删除节点时可能会出现问题 我的图形有6个节点(0到5个)和5个圆弧,如下所示: 5 -> 1 5 -> 0 3 -> 5 4 -> 3 2 -> 3 通过初始化图,我得到了以下后续队列和前置队列: Successors of 0: EMPTY Successors of 1: EMPTY Successors
5 -> 1
5 -> 0
3 -> 5
4 -> 3
2 -> 3
通过初始化图,我得到了以下后续队列和前置队列:
Successors of 0: EMPTY
Successors of 1: EMPTY
Successors of 2: 3
Successors of 3: 5
Successors of 4: 3
Successors of 5: 1 0
Predecessors of 0: 5
Predecessors of 1: 5
Predecessors of 2: EMPTY
Predecessors of 3: 4 2
Predecessors of 4: EMPTY
Predecessors of 5: 3
它们由loadingGraph()函数初始化(该函数工作正常,因为它返回正确的结果而没有问题)
这是我正在使用的图形结构。当然,我会这样做
typedef struct {
int content;
struct cell* next;
} cell;
typedef struct {
cell* start;
cell* end;
} queue;
typedef struct {
int numberNode;
int numberArc;
queue *successors;
queue *predecessors;
} graph;
这是主要的节目:
int main() {
int i, j, k;
int loopTime = 0;
queue *nodeTopologicalOrder = malloc(sizeof (queue));
graph *g = malloc(sizeof (graph));
int *done = calloc(g->numberNode, sizeof (int));
loadingGraph(g);
while (loopTime < 2) {
for (i = 0; i < g->numberNode; i++) {
// If the node i does not have predecessors then
if (((g->predecessors[i]).start == NULL) && (done[i] == 0)) {
// It is deleted from the graph and from the nodes having i as predecessor in their predecessors queues
for (j = 0; j < g->numberNode; j++) {
deleteElement(&(g->predecessors[j]), i);
}
// The node i is added to the topological queue and won't be re-processed.
done[i] = 1;
add(i, nodeTopologicalOrder);
}
}
loopTime++;
}
printf("\nTopological Order :");
display(*nodeTopologicalOrder);
return 0;
}
我的问题似乎出在deleteElement()函数中,但当我测试它时,它就很好了!如果队列中有匹配的元素,它将删除该元素,否则它将按原样返回队列。但当我在主函数中使用它时,它似乎删除了整个队列,或者可能存在做作的问题,但我无法理解。下面是我正在使用的另一个函数(很抱歉有这么多代码):
如果有人能帮上忙,我真的很感激,我知道这里面有很多代码,但是当我没有完全给出的时候,人们通常会说缺少一些代码。。。但我担心太多的代码会吓跑你们
非常感谢 你能把
队列的定义张贴出来吗。您担心的是“最小”,更大的问题是当前的“完整”。它还看起来像是节点拓扑顺序
,在第一次调用add()
之前,malloc
没有初始化。通常有多个有效的拓扑排序。你能描述一下你的算法是如何运行的吗?例如,如果可以首先列出两个节点,您希望是哪一个?如果有两个节点,则顺序在这里并不重要。我将添加队列定义。
Topological Order :2 3 4 5 0 1
void add(int a, queue* pQ) {
cell* new = malloc(sizeof(cell));
(*new).content = a;
(*new).next = NULL;
if (empty(*pQ)){
pQ->start = new;
} else {
(pQ->end)->next = new;
}
pQ->end = new;
}
int pop_first_cell(queue* pQ) {
int deleted_queue_content = -1;
if (pQ == NULL){
exit(EXIT_SUCCESS);
}
if (pQ->start != NULL) {
cell* temp = pQ->start;
deleted_queue_content = temp->content;
pQ->start = temp->next;
free(temp);
}
return(deleted_queue_content);
}
void deleteElement(queue* pQ, int element) {
int contentTemp;
queue *queueTemp = malloc(sizeof (queue));
*queueTemp = create();
while (contentTemp != -1) {
contentTemp = pop_first_cell(pQ);
if (contentTemp != element && contentTemp != -1) {
add(contentTemp, queueTemp);
}
}
*pQ = *queueTemp;
}