最近可能状态不太好,繁琐的事情有点多,效率也没有那么高,这段代码弄的也头痛,这次添加了一些功能,后续还是会慢慢改进,先附上代码和运行结果图给大家看看:
#include"stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Book
{
public:
int num;
float price;
Book*next;
};
Book*head=NULL;
bool check(string str)
{
for(int i=0;i<str.length();i++)
{
if((str[i]>'9'||str[i]<'0')&&(str[i]!=','))
return false;
else
return true;
}
}
Book*creat()
{
Book*p1,*p2;
p1=new Book;
head=p1;
p2=p1;
cout<<"请输入图书的编号,以0结束"<<endl;
string str;
cin>>str;
while(!check(str))
{
cout<<"输入的不是数字,请重新输入,按0返回!"<<endl;
cin>>str;
}
p1->num=atoi(str.c_str());//这里将字符串转换为整数
if(p1->num!=0)
{
cout<<"请输入图书的价格:"<<endl;
cin>>str;
while(!check(str))
{
cout<<"输入的不是数字,请重新输入,按0返回!"<<endl;
cin>>str;
}
p1->price=atof(str.c_str());//这里将字符串转换为浮点型变量
}
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>>str;
while(!check(str))
{
cout<<"输入的不是数字,请重新输入,按0返回!"<<endl;
cin>>str;
}
p1->num=atoi(str.c_str());
if(p1->num!=0)
{
cout<<"请输入图书的价格:"<<endl;
cin>>str;
while(!check(str))
{
cout<<"输入的不是数字,请重新输入,按0返回!"<<endl;
cin>>str;
}
p1->price=atof(str.c_str());
}
p2->next=p1;
}
delete p1;
p2->next=NULL;
return head;
}
void showbook(Book*head)
{
cout<<endl;
cout<<"图书信息如下:"<<endl;
while(head)
{
cout<<"图书的编号为:"<<head->num<<"\t";
cout<<"价格: "<<head->price<<endl;
head=head->next;
}
}
void Delete(Book*head,int num)
{
Book*i;
if(head->num==num)
{
i=head;
head=head->next;
::head=head;
delete head;
cout<<"删除成功"<<endl;
return;
}
while(head)
{
if(head->next==NULL)
{
cout<<"找不到需要删除的编号。"<<endl;
return;
}
if(head->next->num==num)
{
i=head->next;
head->next=i->next;
delete i;
cout<<"删除成功.";
return;
}
head=head->next;
}
}
void insert1(Book*head,int num,float price)
{
Book*l;
Book*list=new Book;
while(head)
{
l=head;
head=head->next;
}
l->next=list;
list->num=num;
list->price=price;
list->next=NULL;
}
void insert2(Book*head,int num,float price)
{
Book*list=new Book;
list->num=num;
list->price;
list->next=head;
::head=list;
}
void insert3(Book*head,int num,float price)
{
Book*list=new Book;
list->num=num;
list->price=price;
if(num<=head->num)
{
list->next=head;
::head=list;
return ;
}
Book*temp=NULL;
while((num>head->num)&&(head->next!=NULL))
{
temp=head;
head=head->next;
}
if(num>head->num)
{
head->next=list;
}
else
{
temp->next=list;
list->next=head;
}
}
int getbooknum(Book*head)
{
int num=0;
while(head)
{
num++;
head=head->next;
}
return num;
}
int main()
{
head=creat();
showbook(head);
int BookNum;
cout<<"请输入需要删除的序号:"<<endl;
cin>>BookNum;
Delete(head,BookNum);
showbook(head);
cout<<"请输入需要添加书籍的序号: "<<endl;
cin>>BookNum;
cout<<"请输入添加书籍的价格: "<<endl;
float BookPrice;
cin>>BookPrice;
insert3(head,BookNum,BookPrice);
showbook(head);
cout<<"图书的数目是:"<<getbooknum(head)<<endl;
system("pause");
return 0;
}