c++程序出错了
下面是一个建立单链表的程序,程序调试编译没有错误,但是执行有错啊,请大神指路!
#include<iostream>
using namespace std;
struct node
{
int no;
struct node *next;
};
class linklist
{
node *h;
public:
linklist();
void creat(int *);
int len();
void del(int i);
void disp();
};
linklist::linklist()
{
h=NULL;
}
void linklist::creat(int *a)
{
node *ptr;
ptr=h;
int i=0;
while(a[i])
{
node *p=new node;
p->no=a[i];
if(ptr==NULL)
ptr=p;
else
ptr->next=p;
p=NULL;
i++;
}
}
int linklist::len()
{
node *p=h;
int count=0;
while(p)
{
count++;
p=p->next;
}
return count;
}
void linklist::del(int i)
{
node *hp=h;
node *s;
int count=1;
while(hp->next)
{
count++;
if(count==i)
{
s=hp->next;
hp->next=hp->next->next;
delete s;
}
}
}
void linklist::disp()
{
node *hp=h;
while(hp!=NULL)
{
cout<<hp->no<<" ";
hp=hp->next;
}
}
void main()
{
int a[]={4,9,6,7,3,2,89,54,69,21};
linklist A;
A.creat(a); //建立一个不带头结点的单链表
cout<<"该链表的长度为:"<<A.len()<<endl;//输出单链表的长度
A.disp();//遍历单链表
A.del(3);//删除单链表第n个元素
cout<<"该链表的长度为:"<<A.len()<<endl;
A.disp();
}
[解决办法]
程序帮你改好了!那你的意思的! 看看注释吧!
#include<iostream>using namespace std;struct node{ int no; struct node *next;};class linklist{ node *h; // 指向第一个节点的指针public: linklist(); void creat(int *,int n); int len(); void del(int i); void disp();};linklist::linklist(){ h=NULL;}void linklist::creat(int *a,int n){ node *ptr; // 指向最后一个节点的指针 ptr=h; int i=0; while(i!=n) { node *p=new node; // p表示指向当前新申请的节点的指针 p->no=a[i]; p->next=NULL; // 节点初始化必不可少! if(ptr==NULL){ ptr=p; h=ptr; } else{ ptr->next=p; ptr=ptr->next; } // p=NULL; i++; }}int linklist::len(){ node *p=h; int count=0; while(p) { count++; p=p->next; } return count;}void linklist::del(int i){ node *hp=h; node *s; int count=1; while(hp->next) { count++; if(count==i) { s=hp->next; hp->next=hp->next->next; delete s; } hp=hp->next; // 这个不能忘呀! }}void linklist::disp(){ node *hp=h; while(hp!=NULL) { cout<<hp->no<<" "; hp=hp->next; }}void main(){ int a[]={4,9,6,7,3,2,89,54,69,21}; linklist A; A.creat(a,sizeof(a)/sizeof(a[0])); //建立一个不带头结点的单链表 // 对于一个数组而言,传过去的指针将蜕变成一般的指针!也就是会丢失掉数组的大小信息!所以一定要将数组的大小传过去! cout<<"该链表的长度为:"<<A.len()<<endl;//输出单链表的长度 A.disp();//遍历单链表 A.del(3);//删除单链表第n个元素 cout<<"该链表的长度为:"<<A.len()<<endl; A.disp();}