1

所以我有下面的代码片段......

for(int k=0; k<10; k++){
    State newState;
    newState = queue.dequeue();
    //...do stuff with `newState`...
}

我遇到的问题是,经过数小时的测试,我意识到每次代码到达时都会newState将完全相同的实例出列,而不是以 FIFO 方式弹出一个新元素......我似乎无法弄清楚找出我到底做错了什么:/StatenewState = queue.dequeue()

下面是我的队列类 .h 和 .cpp 代码...

//queue.h

#include <iostream>
#include <stdio.h>

#include "state.h"

using namespace std;

// Node class
class Node {
public:
    State elem;
    Node* next;
    Node() {}
    State Elem() { return elem; }
    Node* Next() { return next; }
};

// Queue class
class Queue {
    Node *head;
    Node *tail;
  public:
    Queue();
    ~Queue();
    bool isEmpty();
    int size();
    void enqueue(State);
    State dequeue();
};

和我的 .cpp 文件...

//queue.cpp

#include "queue.h"

#include <iostream>

Queue::Queue(){
    head = NULL;
    tail = NULL;
}

Queue::~Queue(){
    if(!isEmpty()){
        while(head){
            Node *del = head;
            head = head->next;
            delete del;
        }
    }
}

bool Queue::isEmpty(){
    return head == NULL;
}

int Queue::size(){
    int count = 0;
    if(isEmpty()){
        return count;
    } else {
        Node *temp = head;
        while(temp){
            temp = temp->next;
            count++;
        }
        delete temp;
        return count;
    }
}

//insert s to back of queue
void Queue::enqueue(State s){
    Node* newNode = new Node();
    newNode->elem = s;
    newNode->next = NULL;
    if(s.checkZ()){
        cout << "Puzzle solved!" << endl << endl;
        exit(0);
    }
    if(head==NULL){
        head = tail = newNode;
    } else {
        tail->next = newNode;
        tail = newNode;
    }
}

//remove State from front of queue
State Queue::dequeue(){
    if(isEmpty()){
        cout << "This puzzle has no solution." << endl;
        cout << "Exiting program..." << endl << endl;
        exit(0);
    } else {
        State ret = head->Elem();
        Node *del = head;
        head = head->next;
        delete del;
        return ret;
    }
}

提前感谢您的帮助,我很乐意根据请求显示我的代码的任何其他片段

编辑:这是我的状态复制构造函数......

State::State(const State &rhs){
    pieces = rhs.pieces;
    pieceCount = rhs.pieceCount;
    rows = rhs.rows; cols = rhs.cols;
    currentState = rhs.currentState;
    prevStates = rhs.prevStates;
    prevStateCount = rhs.prevStateCount;
    moves = rhs.moves;
    moveCount = rhs.moveCount;
}
4

1 回答 1

0

size()

delete temp;

虽然不危险,但因为此时 temp 为空,它看起来很可疑。您还可以删除if/else因为counthead 为空时不递增。

否则我看不出为什么它应该一次又一次地返回相同的元素。唯一的原因可能是一些代码,它多次插入相同的元素。

于 2013-02-22T10:12:55.043 回答