简体   繁体   中英

Linked list pointers

I have a problem with pointers. I'm trying to do a breadth-first state space search using a linked list queue, but I have trouble creating the queue (or rather linking it together). Here's the snippet:

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

What went wrong? queueBegin->next is not being assigned to anything, even though it should (a possible state has been found).

Trouble following the code but I can see trouble

QUEUE_ELEMENT *queueEnd;
queueBegin->next = queueEnd;

queueEnd is an uninitialised variable.

Looking more I'm guessing you want queueEnd to point to the end of the queue and when expandState returns non NULL you want to append the new state to the queue. Unfortunately the code you've written doesn't do anything like that. I'm guessing somewhat but this looks a bit closer

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

Also I can't see any part of the code where you take items off the front of the queue. That's normally what you would do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM