链表指针

Linked list pointers

本文关键字:指针 链表      更新时间:2023-10-16

我有一个指针的问题。我正在尝试使用链表队列进行广度优先状态空间搜索,但是我在创建队列(或者更确切地说将其链接在一起)时遇到了麻烦。下面是代码片段:

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->next没有被分配给任何东西,即使它应该(已经找到一个可能的状态)。

代码有问题,但我可以看到问题

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;
        }

我也看不出代码的任何部分,你把项目从队列的前面。这是你通常会做的