访问尾部>上一个时出错



因此,我正在构建一个创建双链接队列的函数,并且我必须能够遍历列表,向下递增每个节点的数据,直到它达到零或满足条件。由于某种原因,当我运行queueTotal函数时,当最后一个节点的数量= 0,并且它转到queueTotal中的else函数时,我得到了一个段错误。我想这是因为我试图访问tail->prev,而它从未被声明过。那么如何访问前一个节点呢?

isEmpty ():

bool List::isEmpty() { 
    return head == 0;
}

类构造函数:

List::List() {
    head=0;
    tail=0;
}

重载=:

List::Node* List::operator= (Node* input) {
    Node* cell = new Node;
    cell->amount = input->amount;
    cell->price = input->price;
    cell->next = input->next;
    cell->prev = input->prev;
    return cell;
}
push (enqueue)函数:
void List::push(int amount, double price) {
    Node* cell = new Node;
    cell->amount = amount;
    cell->price = price;
    if(isEmpty()) {
            tail = cell;
    }

    else {
            head->prev = cell;
    }
    cell->next = head;
    head = cell;

queueTotal(出列)功能:

double List::queueTotal(int total, double price) {
    Node * cell = new Node;
            this->ListPrint();
    if (isEmpty()) std::cout << "Attempting to dequeue empty queue" << std::endl;
    cell = tail;
    double basis = 0.0;
    double gain = total * price;
    for (int i = 0; total; i++) {
            if(cell->amount > 0) {
                    cell->amount -= 1;
                    total -= 1;
            }
            else {
                    basis += (i * cell->price);
                    i = 0;
                    if(head->next == 0) {
                            head = 0;
                    }
                    else{
                            tail->prev->next = 0;
                    }
                    tail = tail->prev;
            }
    }
    double subtotal = gain - basis;
    totalGain += subtotal;
    return subtotal;
}

在push函数中if(isEmpty()) {tail =cell;头=细胞;因为你需要初始化头部

相关内容

  • 没有找到相关文章

最新更新