链表中的小问题,求解!!!
大家好,小弟才学C++。在编程中出了个问题,这个一运行输入"0"就崩溃了。如果先输入别的数,再输‘0’则正常。在删除中。删除第一个节点,就崩溃。其它的节点可删除。请高手指教!!!!谢谢!!!#include<iostream>
using namespace std;
class book
{
public:
int num;
float price;
book *next;
};
///////////////
book*head=NULL;
///////////////////////////////////////////////
book*creat()
{
book*p1,*p2;
p1=new book;
head=p1;
p2=p1;
cout<<"请输入编号,以0结束"<<endl;
cin>>p1->num;
if(p1->num!=0)
{
cout<<"请输入价格"<<endl;
cin>>p1->price;
}
else{delete p1;p2=NULL;p2->next=NULL;head=NULL;return head;}
while (p1->num!=0)
{
p2=p1;
p1=new book;
cout<<"请输入编号,以0结束"<<endl;
cin>>p1->num;
if(p1->num!=0)
{
cout<<"请输入价格"<<endl;
cin>>p1->price;;
}
p2->next=p1;
}
delete p1;
p2->next=NULL;
return head;
}
///////////////////////////////////////////////////////////
void showbook(book*head)
{
cout<<endl;
while(head)
{
cout<<"编号:"<<head->num<<"\t";
cout<<"价格:"<<head->price<<endl;
head=head->next;
}
}
///////////////////////////////////////////////////
void Delete(book*head,int num)
{
book*l;
if(head->num==num)
{
l=head;
head=l->next;
::head=head;
delete l;
cout<<"操作成功"<<endl;
return;
}
else
{
while(head)
{
if(head->next==NULL)
{
cout<<"没有此编号。"<<endl;
return;
}
if(head->next->num==num)
{
l=head->next;
head->next=l->next;
delete l;
cout<<"成功"<<endl;
return;
}
head=head->next;
}
}
cout<<"找不到编号。"<<endl;
}
/////////////////////////////////////////
int main()
{
book*head=NULL;
head=creat();
showbook(head);
int BookNum;
cout<<"请输入你要删除的编号:";
cin>>BookNum;
Delete(head,BookNum);
showbook(head);
return 0;
}