单个链接列表中的C ++访问冲突读取位置

时间:2013-11-01 21:49:05

标签: c++ visual-studio-2010

我正在使用c ++来实现整数的单个链接列表。我的程序只是要求用户用5个整数填充列表,程序应该删除任何偶数整数并在删除后打印列表。

这是我的代码:

#include <iostream>
using namespace std;
class IntSLLNode
{
public:
    IntSLLNode()     { next = 0; }
    IntSLLNode(int i, IntSLLNode *ptr = 0)
    {
        info = i;
        next = ptr;
    }
    int info;
    IntSLLNode *next;
};
class IntSLList
{
public:
    IntSLList() {head = tail =0; }
    void AddToTail(int);
    void DeleteNode(int);
    void DisplayList();
    void deleteEven();
    IntSLLNode * getHead()
    {
        return head;
    }
private:
    IntSLLNode *head, *tail;
};
void IntSLList::AddToTail(int el)
{
    if (tail != 0) // if list not empty;
    {   tail->next = new IntSLLNode(el);
        tail = tail->next;
    }
    else
        head = tail = new IntSLLNode(el);
}

void IntSLList::deleteEven()
{
IntSLLNode *current;
current=head;
int  num;
while (current!=0)
{
    num=current->info;
    current=current->next;
    if(num%2==0)
    {
        DeleteNode(num);
    }
}
}
void IntSLList::DeleteNode(int el)
{
    if(head !=0)
        if(head==tail && el==head->info)
        {
            delete head;
            head=tail=0;
        }
        else if(el==head->info)
        {
            IntSLLNode *tmp=head;
            head=head->next;
            delete tmp;
        }
        else
        {
            IntSLLNode *pred, *tmp;
            for(pred=head, tmp=head->next;
                tmp!=0 && !(tmp->info==el);
                pred=pred->next, tmp=tmp->next);
            if(tmp!=0)
            {
                pred->next=tmp->next;
                if(tmp==tail)
                    tail=pred;
                delete tmp;
            }
        }
}

void IntSLList::DisplayList()
{
    IntSLLNode *current;
    current=head;
    if(current==0)
        cout<<"Empty List!";
    while (current!=0)
    {
        cout<<current->info<<" ";
        current=current->next;
    }
}

我在ex4.exe中的0x002c1744处获得了未处理的异常:0xC0000005:访问冲突读取位置0xfeeefeee in statment int num = current-&gt; info;任何人都可以建议如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我不确定这一点,但我认为问题在于:

void IntSLList::deleteEven()
{
    IntSLLNode *current;
    current=head;
    while (current!=0)
    {
        if(current->info%2==0)
            DeleteNode(current->info);
        current=current->next; // this line
    }
}

我认为在if语句中执行的已删除节点与下一行之间存在关联。如果删除指向DeleteNode()中某个元素的特定指针,那么到目前为止可能被删除的current将指向错误的地址。

修改

void IntSLList::deleteEven()
{
    IntSLLNode *current;
    current=head;
    while (current!=0)
    {
        if(current->info%2==0)
        {
            int ind = current->info;

            current=current->next;
            DeleteNode(ind);
        }
        else
        {
          current=current->next;
        }
    }
}