EXC_BAD_ACCESS使用链接列表时出错

时间:2014-07-29 14:09:24

标签: c++ linked-list exc-bad-access

我的程序仍然会根据输入的数据文件进行编译和打印。但是,在打印完所有内容后仍然会出现错误,因此程序不能完全结束。

我在程序的这一部分明确地得到了错误

while (current->next != tail)

基本上,该程序使用链接列表来存储信息并将其输出到屏幕中。我的特殊错误是clear()函数,它应该用pop_back()函数清除整个链表。

//removes the last object from the linked list – deallocates memory
template <typename T>
void LL<T>::pop_back()
{

    if(count==0)
    {
        //Do nothing. Nothing to remove.
        return;
    }
    else{
        Node<T> *current;
        current=head;

        while (current->next != tail)
        {
            current=current->next;

        }

        delete tail;
        tail=current;

        count--;
    }
}

//Clears the linked list
template <typename T>
void LL<T>::clear()
{
    Node<T> *current= head;


    while (current != NULL)
    {
    pop_back();
    //current=tail;
}
current=tail;

head=tail=NULL;

}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

你的pop_back方法不处理尾部和头部是相同元素(也就是1个元素的链表)的情况。作为一个快速修复可能是对该案件的额外检查?

if(count==0)
{
    //Do nothing. Nothing to remove.
    return;
}
else if (count==1)
{
    head = tail = NULL;
    count--;
    return;
}

此循环也是无限的,如下所示:

while (current != NULL)
{
    pop_back();
    //current=tail;
}

可能while (head != NULL)while (count != 0)

答案 1 :(得分:0)

您需要在删除节点之前更新节点。以下是pop_back()方法的简化版:

template <typename T>
void LL<T>::pop_back()
{
    Node<T> curr = head;
    Node<T> prev = NULL;

    while(curr != NULL && curr->next != NULL) // I'm assuming your tail's value is NULL
    {
        prev = curr;
        curr = curr->next;
    }

    if(curr != NULL)
    {
        if(prev != NULL)
            prev->next = NULL;
        delete curr;
        --count;
        if(count == 0)
            head = NULL;
    }
}

我没有编译代码,但我认为这个想法很明确。

顺便说一句,您可以提高clear()方法的效果:

Node<T> curr = head;
while(curr != NULL)
{
    Node<T> tmp = curr->next;
    delete curr;
    curr = tmp;
}

head = NULL;
tail = NULL;
count = 0;