访问tail-> prev时出错

时间:2016-10-23 03:17:09

标签: c++ linked-list

所以我构建了一个创建双向链接队列的函数,我必须能够遍历列表,递增每个节点的数据,直到它达到零或满足条件。出于某种原因,当我运行queueTotal函数时,当最后一个节点的数量= 0,并且它进入queueTotal中的else函数时,我得到一个段错误。我想这是因为我试图访问tail-> prev并且它从未被声明过。那么如何访问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;
}

推(入队)功能:

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(dequeue)函数:

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;

}

1 个答案:

答案 0 :(得分:0)

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