C ++:从链表中提取值

时间:2013-01-12 19:29:43

标签: c++ linked-list

当我多次拨打extractMin()时,此代码崩溃了。我认为这应该是显而易见的 你们中的一些问题在于函数,因为我是指针新手,可能是一个明显的错误。因此,除了函数应该使用<运算符检索字典最小值,然后从链表中删除该值之外,您应该知道它是链接列表而不进行详细说明就足够了。

string LinkedListPQueue::extractMin() {
    if (this->isEmpty()) throw ErrorException("Empty queue.");
    string front = LEX_HIGH;
    cell *old;

    for (int i = 0; i < this->size(); i++) {
        if (this->head->value < front) {
            front = this->head->value;
            old = this->head;
        }

        old = this->head;
        this->head = this->head->next;
    }

    logSize--;
    delete old;
    return front;
}



void LinkedListPQueue::enqueue(const string& elem) {
    cell *newCell = new cell;
    newCell->value = elem;
    newCell->next = NULL;
    if(this->isEmpty()) {
        this->head = this->tail = newCell;
        logSize++;

    } else {
        recurSort(newCell);
        this->tail->next = newCell;
        this->tail = newCell;
        logSize++;
    }
}

3 个答案:

答案 0 :(得分:1)

您的head被修改但在运行后从未重置

您应该只使用iterators或只是添加一个以head开头的指针并移动此指针而不是“破坏”列表的head

答案 1 :(得分:1)

您正在修改extractMin()中的头部成员,这会使列表中断。

答案 2 :(得分:1)

问题在于这个循环:

for (int i = 0; i < this->size(); i++) {
    if (this->head->value < front) {
        front = this->head->value;
        old = this->head;
    }

    old = this->head;
    this->head = this->head->next;
}

对我来说似乎过时了,但它也会导致内存泄漏,导致列表在执行后只有一个元素。

对我来说这两行:

old = this->head;
this->head = this->head->next;

不应该在循环中。函数逻辑应该有点复杂 - 你找到一个指向最小元素的指针,然后你用头交换它的值,然后你移除头。

相关问题