中易网

c++链表问题,总是出现unhandle exception

答案:2  悬赏:30  
解决时间 2021-04-21 02:06
#include
#include
using namespace std;
class linkedlist{
struct node{
node*next;
int data;
};
node*head;
int length;
public:
linkedlist():head(),length(){}
~linkedlist();
bool isempty(){return head==0;}
int size()const{return length;}
void clear();
bool find(int index,int&x)const;
int search(const int&x);
void delete_a_element(int k);
void insert_a_element(int k,const int &data);
void travell()const;
};
void linkedlist::clear(){
node*p=head;
node*q;
while(p){
q=p;
delete p;
p=q->next;
}
head=NULL;
length=0;
};
linkedlist::~linkedlist(){
clear();
};
bool linkedlist::find(int index,int&x)const{
if(index>length||index<0){
return false;
}
node*p=head;
for(int i=1;i p=p->next;
}
x=p->data;
return true;
};
int linkedlist::search(const int&x){
node*p=head;
int index=1;
while(p&&p->data!=x){
p=p->next;
index++;
}
if(p){return index;}
return 0;
};
void linkedlist::delete_a_element(int k){
node*p=head;
if(!p||k<0){
cout<<"error1"< }
if(k==1){
head=head->next;
length--;
}
else{
node*q=head;
for(int i=1;i q=q->next;
}
if(q&&q->next)
{p=q->next;
q->next=p->next;
}
delete p;
length++;
}
};
void linkedlist::insert_a_element(int k,const int &data){
node*p=head;
if(k>length||k<0){
cout<<"error2"< }
if(k==0){
node *q=new node;
q->data=data;
length++;
q->next=head;
head=q;
}
else{
node*q=new node;
q->data=data;
for(int i=1;i p=p->next;
}
q->next=p->next;
p->next=q;
length++;
}
};
void linkedlist::travell()const{
node*p=head;
while(p){
cout<data;
p=p->next;
}
};
int main(){
linkedlist list;
list.insert_a_element(0,1);
list.insert_a_element(0,2);
list.insert_a_element(0,3);
list.insert_a_element(0,4);
list.insert_a_element(0,5);
list.insert_a_element(0,6);
list.travell();
char c;
cin>>c;
};
最佳答案
其实你自己可以调试,问题很简单,2个地方有错误,head没有初始化,
在这里加上一句linkedlist():head(),length(){ head=NULL;} 则在执行travell()的时候不会因为找不到末尾节点而挂掉,另外 在释放资源的时候 函数逻辑错了,应该是这样void linkedlist::clear(){

node*p=head;
node*q;
while(p){
q=p;
p=q->next;
delete q;

}
head=NULL;
length=0;
};
全部回答
同问。。。
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
如果分手,别问我为什么、
守卫剑阁V1.22新隐藏英雄密码
20天一次月经、正常么?该怎么办?
2011快乐大本营4月2号的插曲
有什么方法可以使亲情、友情、爱情永远保持新
西安都有什么大超市
康泽日用品商行地址有知道的么?有点事想过去
西宁哪里有卖这种四季星空灯?
怎样可以提高与女孩的对话时间
市直机关事务管理局和质量技术监督局哪个好?
U盘突然不可以装东西,也不可以删除东西,说是
元一装饰怎么去啊,有知道地址的么
虽然说,在校园里面住宿要和宿舍的同学相处好
我的电脑没声音了?怎么装驱动
学贝司之前需要有吉他的基础吗?
推荐资讯
男生小腿粗大腿细怎么办? 本人偏瘦,不过小
出版数学辅导书最好的出版社是?
都德的小故事
中国工商银行(北关储蓄所)(北新街)地址在什么
浙江高速公路是不是要记重收费了
暑假作业数学。谢谢
香港路商贸城北门地址有知道的么?有点事想过
k234火车苏州站可以托运行李吗
石柱县殡仪馆怎么去啊,有知道地址的么
全中国有多少人叫程梦幻
14岁的孩子鼻梁塌,如果每天捏鼻子能不能让鼻
曾经喜欢自己的人现在成为了我的哥哥!你说这
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?