指针有问题。我正在尝试使用链表队列进行广度优先的状态空间搜索,但是我无法创建队列(或者更确切地说将它们链接在一起)。这是片段:
typedef struct queueList {
STATE *state;
queueList *next;
queueList(STATE *state): state(state), next(NULL) {}
~queueList() {delete next;}
} QUEUE_ELEMENT;
void moveAround(STATE *start) {
QUEUE_ELEMENT *queueBegin = new QUEUE_ELEMENT(start);
QUEUE_ELEMENT *queueEnd;
queueBegin->next = queueEnd;
while (queueBegin != NULL) {
STATE *current = queueBegin->state;
if (compareStates(current,finish) == 1) {
answer = current;
return;
}
for (int i = 0; i < 12; i++) {
STATE *newState = expandState(current, i);
if (newState != NULL) {
queueEnd = new QUEUE_ELEMENT(newState);
queueEnd = queueEnd->next;
}
}
queueBegin = queueBegin->next;
}
}
出了什么问题? queueBegin-&gt; next没有被分配给任何东西,即使它应该(已找到可能的状态)。
答案 0 :(得分:0)
麻烦关注代码,但我可以看到麻烦
QUEUE_ELEMENT *queueEnd;
queueBegin->next = queueEnd;
queueEnd
是一个未初始化的变量。
查看更多我猜你希望queueEnd指向队列的末尾,当expandState返回非NULL时,你想要将新状态附加到队列。不幸的是,你写的代码没有做那样的事情。我猜有点但这看起来更接近
QUEUE_ELEMENT *queueBegin = new QUEUE_ELEMENT(start);
QUEUE_ELEMENT *queueEnd = queueBegin;
...
STATE *newState = expandState(current, i);
if (newState != NULL) {
QUEUE_ELEMENT *newQueueEnd = new QUEUE_ELEMENT(newState);
queueEnd->next = newQueueEnd;
queueEnd = newQueueEnd;
}
此外,我看不到代码的任何部分,您将项目从队列前面取出。这通常是你要做的。