读书人

新人求教一个VS2008报的异常

发布时间: 2013-08-01 15:23:18 作者: rapoo

新人求教一个VS2008报的错误
单链表.exe 中的 0x001b193d 处未处理的异常: 0xC0000005: 读取位置 0x00000004 时发生访问冲突
附上我写的代码:
A.h


#ifndef A_H
#define A_H
#include<iostream>
using namespace std;
template<class T>
struct Node
{
T data;
Node * next;
};
template<class T>
class LinkList
{
public:
LinkList(T a[],int n=0)
{
Node<T> * p;
head=new Node<T>;
head->next=NULL;
head->data=0;
for(int i=0;i<n;i++)
{
p=new Node<T>;
p->data=a[i];
p->next=head->next;
head->next=p;
}
cout<<"调用构造函数成功!"<<endl;
}
~LinkList();
bool IsEmpty();
T GetNode(int i);
int length();
int LocateNode(T x);
LinkList<T> & Insert(int i,T x);
LinkList<T> & Delete(int i);
void ShoeList();
private:
Node<T> * head;
};
#endif

A.CPP

#include"A.h"
/*
template<class T>
LinkList<T>::LinkList(T a[], int n )
{
Node<T> * p;
head=new Node;
head->next=NULL;
head->data=0;
for(int i=0;i<n;i++)
{
p=new Node;
p->data=a[i];
p->next=head->next;
head->next=p;
}
cout<<"调用构造函数成功!"<<endl;
}*/
template<class T>
LinkList<T>::~LinkList()
{
Node<T> * a=head;
while(a->next!=0)
{
delete a;
a=a->next;
}
}
template<class T>
bool LinkList<T>::IsEmpty()
{
return head->next==0;
}
template<class T>
T LinkList<T>::GetNode(int i)
{
int j=0;
Node * x=head;
while(j++!=i)
{
x=x->next;
}
return x->data;
}
template<class T>
int LinkList<T>::length()
{
int i=0;
Node * x=head;
while(x->next!=0)
{
i++;
x=x->next;
}
return i;
}
template<class T>
int LinkList<T>::LocateNode(T x)
{
int i=0;
Node<T> * y=head;
while(y->data!=x)
{
i++;
y=y->next;
}
return i;
}
template<class T>
LinkList<T> & LinkList<T>::Insert(int i, T x)
{
int j=0;


Node<T> * s=head;
while(j<i&&(s->next!=NULL))
{
j++;
s=s->next;
}
Node<T> * y=new Node<T>;
y->data=x;
y->next=s->next;
s->next=y->next;
return *this;
}
template<class T>
LinkList<T> & LinkList<T>::Delete(int i)
{
if(IsEmpty())
cout<<"删除失败!"<<endl;
else
{
int j=0;
Node<T> * x=head;
while(j<i)

x=x->next;
Node<T> * y=x->next;

x->next=y->next;
delete y;
}
return *this;
}
template<class T>
void LinkList<T>::ShoeList()
{
Node<T> * x=head;
while((x->next)!=NULL)
{
x=x->next;
cout<<x->data<<" ";

}
cout<<endl;
}


main.CPP

#include"A.h"
#include"A.cpp"
void main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
LinkList<int> ll(a,10);
ll.ShoeList();
int x=11;
ll.Insert(9,x);
ll.ShoeList();
cout<<"x在单链表中的位置为:"<<ll.LocateNode(x)<<endl;
ll.Delete(10);
ll.ShoeList();
getchar();
}
vs2008 单链表 报错
[解决办法]
三个错误:
1. LocateNode 中的 while 没有判读是否到尾了. 改成


while(y != NULL && y->data!=x)


2. Delete 函数中的

while(j<i)

x=x->next;


循环里面既不改变 i, 又不改变 j, 死循环. 知道 x 访问到尾后崩溃.
另外, 位置得找要删除的前一个, 改它的 next 指针, 所以改成:


while(j<i-1)
{
x=x->next;
++j;
}


3. 析构函数里面

delete a;
a=a->next;


a 刚刚 delete 了, 还去使用 a->next ? 这不是找死么...




while(a->next!=0)
{
Node<T> * t=a;
a=a->next;
delete t;
}

读书人网 >C++

热点推荐