0

我正在使用 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:在声明 int num=current->info 中访问冲突读取位置 0xfeeefeee;谁能建议如何解决这个问题?

4

1 回答 1

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;
        }
    }
}
于 2013-11-01T22:13:54.180 回答